Directing a profile

MongoDB is an open source database system based on distributed file storage written in C++ language.

Adding more nodes can ensure server performance under high load conditions.

MongoDB aims to provide scalable, high-performance data storage solutions for WEB applications.

MongoDB stores data as a document. The data structure consists of key=>value pairs. MongoDB documents are similar to JSON objects. Field values can contain other documents, arrays, and document arrays.

The main features

  • MongoDB is a document storage oriented database, operation is relatively simple and easy.
  • You can index any attribute in the MongoDB record (e.g. FirstName=”Sameer”,Address=”8 Gandhi Road”) for faster sorting.
  • You can create data images locally or over the network, which makes MongoDB more scalable.
  • If the load increases (requiring more storage space and more processing power), it can be distributed to other nodes in the computer network this is called sharding.
  • Mongo supports rich query expressions. Query instructions use JSON-style tags to easily query objects and arrays embedded in documents.
  • MongoDb uses the update() command to replace completed documents (data) or some specified data fields.
  • Map/ Reduce in Mongodb is used to process and aggregate data in batches.
  • Map and Reduce. The Map function invokes emit(key,value) to traverse all records in the set and send the key and value to the Reduce function for processing.
  • The Map and Reduce functions are written in Javascript, and mapReduce operations can be performed using db.runCommand or mapReduce command.
  • GridFS is a built-in feature in MongoDB that can be used to store a large number of small files.
  • MongoDB allows script execution on the server side. You can write a function in Javascript and execute it directly on the server side. You can also store the function definition on the server side and call it directly next time.
  • MongoDB supports a variety of programming languages :RUBY, PYTHON, JAVA, C++, PHP, C# and more.
  • MongoDB installation is simple

Install MongoDB on Linux

MongoDB provides 64-bit installation packages for Linux distributions, which you can download from the official website.

MongoDB source download address: www.mongodb.com/download-ce…

We need to install each Linux platform dependency package before installation.

Red Hat/CentOS:

sudo yum install libcurl openssl
Copy the code

Ubuntu 18.04 LTS (“Bionic”)/Debian 10 “Buster” :

sudo apt-get install libcurl4 openssl
Copy the code

Ubuntu 16.04 LTS (“Xenial”)/Debian 9 “Stretch” :

sudo apt-get install libcurl3 openssl
Copy the code

Check out the Ubuntu version

lsb_release -a
Copy the code

Here we select THE TGZ download, download the installation package, and unpack TGZ (the installation on 64-bit Linux is illustrated below).

Wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1604-4.4.10.tgz # download wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1604-4.4.10.tgz # decompressionCopy the code

MongoDB’s executables are in the bin directory, so you can add them to the PATH PATH

export PATH=<mongodb-install-directory>/bin:$PATH
Copy the code

**** is your MongoDB installation path.

Creating a database directory

By default, MongoDB initializes the following two directories:

  • Data storage directory: /var/lib/mongodb
  • Log file directory: /var/log/mongodb

We can create these two directories before starting:

sudo mkdir -p /var/lib/mongo
sudo mkdir -p /var/log/mongodb
Copy the code

Next start the Mongodb service:

mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --fork
Copy the code

MongoDB background management Shell

If you need to go to mongodb admin, you can directly execute the mongo command file since you have added the mongodb executable to the PATH PATH.

MongoDB Shell is an interactive Javascript Shell of MongoDB, which is used to operate and manage MongoDB.

When you go to mongoDB, it links to the test document (database) by default:

MongoDB Concept Analysis

The basic concepts in mongodb are documents, collections, and databases. The following table will help you understand some of the concepts in Mongo more easily:

SQL terms/concepts MongoDB terminology/concepts Explanation/explanation
database database The database
table collection Database tables/collections
row document Data record line/document
column field Data fields/fields
index index The index
table joins Table joins,MongoDB does not support
primary key primary key Primary key. MongoDB automatically sets the _ID field as the primary key

MongoDB create database

The database

Multiple databases can be created in one mongodb.

The default MongoDB database is “DB”, which is stored in the data directory.

A single instance of MongoDB can hold multiple independent databases, each with its own collection and permissions, and different databases are placed in different files.

The “show DBS “command displays a list of all data.

toby@recsys:~$mongo MongoDB shell version: 2.6.10 connecting to: test > show DBS admin (empty) local 0.078GBCopy the code

Run the “db” command to display the current database object or collection.

toby@recsys:~$mongo MongoDB shell version: 2.6.10 connecting to: test > db testCopy the code

Run the “use” command to connect to a specified database.

toby@recsys:~$mongo MongoDB shell version: 2.6.10 connecting to: test > Use admin switched to db admin > DB admin >Copy the code

grammar

The syntax format for MongoDB to create a database is as follows:

use DATABASE_NAME
Copy the code

If the database does not exist, create the database, otherwise switch to the specified database.

The instance

In the following example, we created the database tobyTest:

toby@recsys:~$mongo MongoDB shell version: 2.6.10 Connecting to: test > use tobytest switched to db tobytest > db tobytest >Copy the code

If you want to see all the databases, use the show DBS command:

> show dbs
admin  (empty)
local  0.078GB
> 
Copy the code

As you can see, the database we just created, TobyTest, is not in the list of databases. To display it, we need to insert some data into the TobyTest database.

> db.tobytest.insert({"name":"Toby"}) WriteResult({ "nInserted" : 1}) > show DBS admin (empty) local 0.078GB tobytest 0.078GB >Copy the code

The default MongoDB database is test. If you do not create a new database, the collection will be stored in test.

Note: In MongoDB, collections are created only after content is inserted! That is, a collection (table) is created before a document (record) is inserted.

MongoDB create a collection

MongoDB uses the createCollection() method to create collections.

Syntax format:

db.createCollection(name, options)
Copy the code

Parameter Description:

  • Name: Name of the collection to be created
  • Options: Optional parameters that specify memory size and index options

Options can be the following parameters:

field type describe
capped Boolean (Optional) If true, a fixed collection is created. A fixed collection is a collection of a fixed size that automatically overwrites the earliest documents when it reaches its maximum.When this value is true, the size argument must be specified.
autoIndexId Boolean This parameter is not supported after 3.2. (Optional) If the value is true, the index is automatically created in the _ID field. The default is false.
size The numerical (Optional) Specify a maximum value, the number of bytes, for a fixed set.This field also needs to be specified if capped is true.
max The numerical (Optional) Specifies the maximum number of documents to contain in a fixed collection.

When inserting a document, MongoDB checks the size field of the fixed collection first, and then the Max field.

The instance

Create tobyCollection in tobyTest database:

> use tobytest
switched to db tobytest
> db.createCollection("tobycollection")
{ "ok" : 1 }
> 
Copy the code

To view existing collections, use the show Collections or show tables command:

> show tables
system.indexes
tobycollection
tobytest
> 
Copy the code

MongoDB delete collection

MongoDB uses the drop() method to drop collections.

Syntax format:

db.collection.drop()
Copy the code

Parameter Description:

  • There is no

The return value

The drop() method returns true if the selected collection was successfully dropped, false otherwise.

The instance

In the database tobyTest, we can first look at existing collections using the show Collections command:

> use tobytest
switched to db tobytest
> show collections
system.indexes
tobycollection
tobytest
> 
Copy the code

Then delete the collection tobyCollection:

> db.tobycollection.drop()
true
> 
Copy the code

Show Collections to see collections in the database tobyTest again:

> show collections
system.indexes
tobytest
> 
Copy the code

You can see from the results that the TobyCollection collection has been deleted.

MongoDB insert document

The data structure of the document is basically the same as JSON.

All data stored in the collection is in BSON format.

BSON is a jSON-like storage format, short for Binary JSON.

Inserted into the document

MongoDB inserts documents into the collection using insert() or save() methods with the following syntax:

Db. COLLECTION_NAME. Insert (document) or the COLLECTION_NAME. Save (document)Copy the code
  • Save () : Updates data if the _ID primary key exists, inserts data if it does not. This method is deprecated in the new version and can be replaced with db.collection.insertone () or db.collection.replaceone ().
  • Insert () : if the primary key of data already exists, will throw org. Springframework. Dao. DuplicateKeyException abnormalities, prompt primary key repeat, do not save the current data.

The instance

The following documents can be stored in the COL collection of MongoDB’s TobyTest database:

> db.col.insert({title:'Toby MongoDB',
... description:'this is MongoDB',
... tags:['mongodb','database','NoSQL'],
... likes:1
... })
WriteResult({ "nInserted" : 1 })
> 
Copy the code

Col is our collection name in the above example, and if the collection is not in the database, MongoDB automatically creates the collection and inserts the document.

View the inserted document:

> db.col.find()
{ "_id" : ObjectId("617970fc286e9ff2b1250d70"), "title" : "Toby MongoDB", "description" : "this is MongoDB", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 1 }
> 
Copy the code

We can also define data as a variable, as follows:

> document=({title:'Toby another MongoDB',
... description:'this is another MongoDB',
... tags:['mongodb','database','NoSQL'],
... likes:2
... })
Copy the code

The following information is displayed:

{
	"title" : "Toby another MongoDB",
	"description" : "this is another MongoDB",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 2
}
Copy the code

Perform the insert operation:

> db.col.insert(document)
WriteResult({ "nInserted" : 1 })
> db.col.find()
{ "_id" : ObjectId("617970fc286e9ff2b1250d70"), "title" : "Toby MongoDB", "description" : "this is MongoDB", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 1 }
{ "_id" : ObjectId("61797229286e9ff2b1250d71"), "title" : "Toby another MongoDB", "description" : "this is another MongoDB", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 2 }
> 
Copy the code

MongoDB Update documentation

MongoDB uses the update() and save() methods to update the documents in the collection. Let’s take a closer look at the two functions and their differences.


The update () method

The update() method is used to update an existing document. The syntax is as follows:

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)
Copy the code

Parameter Description:

  • Query: The query condition is similar to where in the SQL update query.
  • Update: An update object and some update operators (e.g.,,inc…) SQL update set ()
  • Upsert: Optional, this parameter means whether to insert objNew if no update record exists. True is insert, default is false, no insert.
  • Multi: Optional. By default, mongodb updates only the first found record. If this parameter is true, mongodb updates all found records.
  • WriteConcern: Optional, level of exception thrown.

The instance

We insert the following data into the col collection:

> db.col.insert({title:'Toby MongoDB',
... description:'this is MongoDB',
... tags:['mongodb','database','NoSQL'],
... likes:1
... })
WriteResult({ "nInserted" : 1 })
> 
Copy the code

Next we update the title with the update() method:

> db.col.update({'title':'Toby MongoDB'},{$set:{'title':'MongoDB'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find().pretty()
{
	"_id" : ObjectId("617970fc286e9ff2b1250d70"),
	"title" : "MongoDB",
	"description" : "this is MongoDB",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 1
}
{
	"_id" : ObjectId("61797229286e9ff2b1250d71"),
	"title" : "Toby another MongoDB",
	"description" : "this is another MongoDB",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 2
}
> 
Copy the code

You can see that the title has been updated from “Toby MongoDB” to “MongoDB”.

MongoDB delete document

The MongoDB remove() function is used to remove data from the collection.

MongoDB data can be updated using the update() function. It is a good practice to execute find() before executing remove() to determine if the condition is correct.

grammar

The basic syntax of the remove() method looks like this:

db.collection.remove(
   <query>,
   <justOne>
)
Copy the code

If you have MongoDB after version 2.6, the syntax is as follows:

db.collection.remove(
   <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>
   }
)
Copy the code

Parameter Description:

  • Query :(optional) conditions for the document to be deleted.
  • JustOne: (Optional) If this parameter is set to true or 1, only one document is deleted. If this parameter is not set, or the default value false is used, all documents matching the criteria are deleted.
  • WriteConcern :(optional) level of an exception thrown.

The instance

We insert twice in the following documents:

> db.col.insert({title:'Toby MongoDB', description:'this is MongoDB', tags:['mongodb','database','NoSQL'], likes:1 })
WriteResult({ "nInserted" : 1 })
> db.col.insert({title:'Toby MongoDB', description:'this is MongoDB', tags:['mongodb','database','NoSQL'], likes:1 })
WriteResult({ "nInserted" : 1 })
> 
Copy the code

Use find() to query data:

> db.col.find()
{ "_id" : ObjectId("617970fc286e9ff2b1250d70"), "title" : "MongoDB", "description" : "this is MongoDB", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 1 }
{ "_id" : ObjectId("61797229286e9ff2b1250d71"), "title" : "Toby another MongoDB", "description" : "this is another MongoDB", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 2 }
{ "_id" : ObjectId("6179747d286e9ff2b1250d72"), "title" : "Toby MongoDB", "description" : "this is MongoDB", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 1 }
{ "_id" : ObjectId("61797481286e9ff2b1250d73"), "title" : "Toby MongoDB", "description" : "this is MongoDB", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 1 }
> 
Copy the code

Next we remove the document with the title ‘Toby MongoDB’ :

> db.col.remove({'title':'Toby MongoDB'}) WriteResult({"nRemoved" : 2}) # remove two > db.col.find() {"_id" : ObjectId("617970fc286e9ff2b1250d70"), "title" : "MongoDB", "description" : "this is MongoDB", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 1 } { "_id" : ObjectId("61797229286e9ff2b1250d71"), "title" : "Toby another MongoDB", "description" : "this is another MongoDB", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 2 } >Copy the code

If you want to delete only the first record found, set justOne to 1, as shown below:

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
Copy the code

If you want to delete all data, use the following method (similar to the truncate command in regular SQL) :

> db.col.remove({})
WriteResult({ "nRemoved" : 2 })
> db.col.find()
> 
Copy the code

MongoDB query document

MongoDB queries documents using the find() method.

The find() method displays all documents in an unstructured manner.

grammar

The syntax format of MongoDB query data is as follows:

db.collection.find(query, projection)
Copy the code
  • Query: Optional. Use the query operator to specify the query conditions
  • Projection: Optional, using the projection operator to specify the key to return. Query returns all key values in the document, simply omit this parameter (the default is omitted).

If you need to read data in a readable way, you can use the pretty() method, which has the following syntax:

>db.col.find().pretty()
Copy the code

The pretty() method displays all documents in a formatted manner.

The instance

In the following example, we query data from col:

> db.col.insert({title:'Toby MongoDB', description:'this is MongoDB',by:'Toby', tags:['mongodb','database','NoSQL'], likes:100 })
WriteResult({ "nInserted" : 1 })
> db.col.find().pretty()
{
	"_id" : ObjectId("6179772f286e9ff2b1250d75"),
	"title" : "Toby MongoDB",
	"description" : "this is MongoDB",
	"by" : "Toby",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 100
}
> 
Copy the code

In addition to the find() method, there is a findOne() method that returns only one document.

Directing the AND conditions

MongoDB’s find() method can pass in multiple keys, each separated by a comma, the AND condition of regular SQL.

The syntax is as follows:

>db.col.find({key1:value1, key2:value2}).pretty()
Copy the code

The instance

The following example uses the BY and title keys to query Toby MongoDB data

> db.col.find({'by':'Toby','title':'Toby MongoDB'}).prettydb.col.find({'by':'Toby','title':'Toby MongoDB'}).pretty()
{
	"_id" : ObjectId("6179772f286e9ff2b1250d75"),
	"title" : "Toby MongoDB",
	"description" : "this is MongoDB",
	"by" : "Toby",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 100
}
> 
Copy the code

WHERE by=’Toby’ AND title=’Toby MongoDB’


Directing the OR conditions

The MongoDB OR conditional statement uses the keyword $OR, and the syntax format is as follows:

>db.col.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()
Copy the code

The instance

In the following example, we demonstrate a query for a document whose key by value is Toby or whose key title value is Toby MongoDB.

> db.col.find({$or:[{"by":"Toby"},{"title":"Toby MongoDB"}]}).pretty()
{
	"_id" : ObjectId("6179772f286e9ff2b1250d75"),
	"title" : "Toby MongoDB",
	"description" : "this is MongoDB",
	"by" : "Toby",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 100
}
> 
Copy the code

AND AND OR are used together

‘where likes>50 AND (by = ‘Toby’ OR title = ‘Toby MongoDB’)’

> db.col.find({"likes":{$gt:50},$or:[{"by":"Toby"},{"title":"Toby MongoDB"}]}).pretty()
{
	"_id" : ObjectId("6179772f286e9ff2b1250d75"),
	"title" : "Toby MongoDB",
	"description" : "this is MongoDB",
	"by" : "Toby",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 100
}
> 
Copy the code

Directing a sort


Directing the sort () method

In MongoDB, sort() method is used to sort data, sort() method can specify the sorted field by parameter, and use 1 and -1 to specify the sorting method, where 1 is ascending and -1 is descending.

grammar

The basic syntax of the sort() method is as follows:

>db.COLLECTION_NAME.find().sort({KEY:1})
Copy the code

The instance

The col set contains the following data:

> db.col.find().pretty()
{
	"_id" : ObjectId("61797a56286e9ff2b1250d78"),
	"title" : "Toby PHP",
	"description" : "this is PHP",
	"by" : "Toby",
	"tags" : [
		"PHP",
		"Language"
	],
	"likes" : 100
}
{
	"_id" : ObjectId("61797a62286e9ff2b1250d79"),
	"title" : "Toby JAVA",
	"description" : "this is JAVA",
	"by" : "Toby",
	"tags" : [
		"JAVA",
		"Language"
	],
	"likes" : 50
}
{
	"_id" : ObjectId("61797a83286e9ff2b1250d7a"),
	"title" : "Toby Python",
	"description" : "this is Python",
	"by" : "Toby",
	"tags" : [
		"Python",
		"Language"
	],
	"likes" : 20
}
> 
Copy the code

The following example demonstrates the descending order of data in the COL collection for the field likes:

> db.col.find({},{'title':1,_id:0}).sort({"likes":-1})
{ "title" : "Toby PHP" }
{ "title" : "Toby JAVA" }
{ "title" : "Toby Python" }
> 
Copy the code

Python MongoDB


PyMongo

Python requires a MongoDB driver to connect to MongoDB, and here we use the PyMongo driver to connect.

PIP install

PIP is a general-purpose Python package management tool that provides the ability to find, download, install, and uninstall Python packages.

Install pymongo:

$ python3 -m pip install pymongo
Copy the code

Test PyMongo

Next we can create a test file demo_test_mongodb.py with the following code:

import pymongo
Copy the code

Run the preceding code files. If no error occurs, the installation is successful.

Creating a database

Create a database

To create the database, use the MongoClient object and specify the URL of the connection and the name of the database to create.

In the following example, we created the database PyDB:

The instance

import pymongo
myclient=pymongo.MongoClient("mongodb://localhost:27017/")
mydb=myclient["pydb"]
Copy the code

Note: In MongoDB, databases are created only after content is inserted! That is, after the database is created, the collection (data table) is created and a document (record) is inserted before the database is actually created.

Check whether the database already exists

We can read all the databases in MongoDB and determine if the specified database exists:

The instance

import pymongo
myclient=pymongo.MongoClient("mongodb://localhost:27017/")
mydb=myclient["pydb"]

dblist = myclient.list_database_names()
# dblist = myclient.database_names() 
if "pydb" in dblist:
  print("Database exists!")
else:
  print('Database does not exist')
Copy the code

** Note: **database_names is deprecated in the latest version of Python; versions after Python3.7+ have been changed to list_database_names().

Create a collection

Collections in MongoDB are similar to SQL tables.

Create a collection

MongoDB uses database objects to create collections as shown in the following example:

The instance

import pymongo
myclient=pymongo.MongoClient("mongodb://localhost:27017/")
mydb=myclient["pydb"]

mycol=myclient["col_set"]
Copy the code

Note: In MongoDB, collections are created only after content is inserted! That is, a collection (table) is created before a document (record) is inserted.

Determines whether the collection already exists

We can read all collections in the MongoDB database and determine if the specified collection exists:

The instance

import pymongo
myclient=pymongo.MongoClient("mongodb://localhost:27017/")
mydb=myclient["pydb"]

mycol=myclient["col_set"]

collist = mydb. list_collection_names()
if "col_set" in collist:   # check whether the Sites collection exists
  print("Set already exists!")
else:
  print('Set does not exist')
Copy the code

Python Mongodb inserts documentation

A document in MongoDB is like a record in an SQL table.

Insert a collection

Documents are inserted into the collection using the insert_one() method, which takes the dictionary name => value pair as its first argument.

The following instance inserts a document into the col_set collection:

The instance

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
 
mydict = { "name": "Toby"."age": "23"."url": "https://juejin.cn/user/3403743731649863" }
 
x = mycol.insert_one(mydict) 
print(x)
Copy the code

Check on the command line to see if the insert succeeded

> use pydb
switched to db pydb
> db.col_set.find()
{ "_id" : ObjectId("617ce42cbc6011eaf1529012"), "name" : "Toby", "url" : "https://juejin.cn/user/3403743731649863", "age" : "23" }
> 
Copy the code

Insert multiple documents

Multiple documents are inserted into the collection using the insert_many() method, which takes the dictionary list as its first argument.

The instance

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
 
mylist = [
  { "name": "Tom"."age": "100"."url": "https://juejin.cn/user/3403743731649863" },
  { "name": "Mary"."age": "101"."url": "https://juejin.cn/user/3403743731649863" },
  { "name": "Timi"."age": "10"."url": "https://juejin.cn/user/3403743731649863" },
]
 
x = mycol.insert_many(mylist)
 
Print the _id values of all inserted documents
print(x.inserted_ids)
Copy the code

Check on the command line to see if the insert succeeded

> use pydb
switched to db pydb
> db.col_set.find()
{ "_id" : ObjectId("617ce42cbc6011eaf1529012"), "name" : "Toby", "url" : "https://juejin.cn/user/3403743731649863", "age" : "23" }
{ "_id" : ObjectId("617ce591826d13d898f97890"), "name" : "Tom", "url" : "https://juejin.cn/user/3403743731649863", "age" : "100" }
{ "_id" : ObjectId("617ce591826d13d898f97891"), "name" : "Mary", "url" : "https://juejin.cn/user/3403743731649863", "age" : "101" }
{ "_id" : ObjectId("617ce591826d13d898f97892"), "name" : "Timi", "url" : "https://juejin.cn/user/3403743731649863", "age" : "10" }
> 
Copy the code

Python Mongodb query documentation

MongoDB uses find and find_one methods to query data in collections, which are similar to SELECT statements in SQL.

Query a piece of data

We can use the find_one() method to query a single piece of data in the collection.

Query the first data in the col_set document:

The instance

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
 
x = mycol.find_one()
 
print(x)
Copy the code

Query all data in the collection

The find() method queries all data in a collection, similar to the SELECT * operation in SQL.

The following example finds all data in the col_set collection:

The instance

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
  
for x in mycol.find():
  print(x)
Copy the code

Query the data of a specified field

We can use the find() method to query the data for the specified field, and set the value of the field to be returned to 1.

The instance

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
  
for x in mycol.find({},{ "_id": 0."name": 1."age": 1}) :print(x)
Copy the code

Queries queries based on specified conditions

We can set parameters in find() to filter data.

Example Find data where name is “Toby” :

The instance

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
  
myquery = { "name": "Toby" }
 
mydoc = mycol.find(myquery)
 
for x in mydoc:
  print(x)
Copy the code

Returns the specified number of records

If we want to set a specified number of records to a query result, we can use the limit() method, which takes a single numeric argument.

The following example returns three document records:

The instance

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
  
myresult = mycol.find().limit(3)
 
# output result
for x in myresult:
  print(x)
Copy the code

Python Mongodb modified documentation

We can modify records in a document in MongoDB using the update_one() method. The first parameter is the query condition and the second parameter is the field to be modified.

If more than one match is found, only the first match is modified.

The following example changes the age field value 23 to 12345:

The instance

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
  
myquery = { "age": "23" }
newvalues = { "$set": { "age": "12345" } }
 
mycol.update_one(myquery, newvalues)
 
# print the modified "Sites" collection
for x in mycol.find():
  print(x)
Copy the code

The sorting

The sort() method can specify ascending or descending sort.

The first argument to the sort() method is the field to sort, and the second field specifies the sort rule. 1 is ascending, -1 is descending, and the default is ascending.

Sort the age field in ascending order:

The instance

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
  
mydoc = mycol.find().sort("age")
for x in mydoc:
  print(x)
Copy the code

Sort the field age in descending order:

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
  
mydoc = mycol.find().sort("alexa", -1)
 
for x in mydoc:
  print(x)
Copy the code

Python Mongodb deletes data

We can delete a document using the delete_one() method, which takes the query object as its first argument and specifies which data to delete.

Delete a document whose name field is “Timi” :

The instance

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
  
myquery = { "name": "Timi" }
 
mycol.delete_one(myquery)
 
Output after delete
for x in mycol.find():
  print(x)
Copy the code

Delete all documents in the collection

The delete_many() method deletes all documents in the collection if an empty query object is passed in:

The instance

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
  
x = mycol.delete_many({})
 
print(x.deleted_count, "Some documents have been deleted")
Copy the code

Delete the collection

We can use the drop() method to drop a collection.

The following instance removes the col_set collection:

The instance

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
  
mycol.drop()

Copy the code

Let’s check it out at the terminal

> use pydb
switched to db pydb
> show tables
system.indexes
> 
Copy the code

Reference links:

  • www.runoob.com/python3/pyt…

  • www.runoob.com/mongodb/mon…