MongoDB installation and foundation

Posted by saloon12yrd on Mon, 20 Dec 2021 08:12:17 +0100

One of the main reasons MongoDB stores portraits is to facilitate expansion, because the portrait content may be constantly updated with the continuous development of products.

MongoDB syntax (such as addition, deletion, modification, query, sorting, etc.),

Obtain user and news portraits from MongoDB to construct relevant features

Introduction to MongoDB

MongoDB is written in C + + language. It is an open source database system based on distributed file storage. In the case of high load, adding more nodes can ensure the server performance. MongoDB aims to provide scalable high-performance data storage solutions for WEB applications.

MongoDB stores data as a document, and the data structure consists of key value (key = > value) pairs. A MongoDB document is similar to a JSON object. Field values can contain other documents, arrays, and document arrays.

main features

  • MongoDB is a document storage oriented database, which is relatively simple and easy to operate.
  • You can set the index of any attribute in MongoDB records (such as FirstName = "Sameer", Address = "8 Gandhi Road") to achieve faster sorting.
  • You can create data images locally or over the network, which makes MongoDB more scalable.
  • If the load increases (requires more storage space and stronger processing power), it can be distributed on other nodes in the computer network, which is the so-called fragmentation.
  • Mongo supports rich query expressions. The query instruction uses JSON tags, which can easily query the embedded objects and arrays in the document.
  • MongoDb can use the update() command to replace the completed document (data) or some specified data fields.
  • Map/reduce in Mongodb is mainly used for batch processing and aggregation of data.
  • Map and Reduce. The map function calls emit(key,value) to traverse all records in the collection, and passes the key and value to the Reduce function for processing.
  • The Map function and Reduce function are written in Javascript and can be accessed through dB Run command or MapReduce command to perform MapReduce operation.
  • GridFS is a built-in function in MongoDB, which can be used to store a large number of small files.
  • MongoDB allows scripts to be executed on the server. You can write a function in Javascript and execute it directly on the server. You can also store the definition of the function on the server and call it directly next time.
  • MongoDB supports various programming languages: RUBY, PYTHON, JAVA, C + +, PHP, c# and other languages.
  • MongoDB is easy to install

Installing MongoDB on Linux platform

MongoDB provides 64 bit installation packages for various linux distributions. You can download the installation package on the official website.

MongoDB source code download address: https://www.mongodb.com/download-center#community

Ubuntu 18.04 LTS ("Bionic")/Debian 10 "Buster":

sudo apt-get install libcurl4 openssl

View the version of ubuntu

lsb_release -a

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ttfad5sh-1639830975121) (/ home / Lance /. Config / typora / typora user images / image-20211218202844156. PNG)]

Here, we choose tgz download, download the installation package, and unzip tgz (the following demonstrates the installation on 64 bit Linux).

wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1604-4.4.10.tgz # Download
tar -zxvf mongodb-linux-x86_64-ubuntu1604-4.4.10.tgz #decompression

The MongoDB executable is located in the bin directory, so you can add it to the PATH

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

****The installation path of MongoDB for you.

Create database directory

By default, MongoDB will initialize the following two directories after startup:

  • 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

Next, start the Mongodb service:

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

MongoDB background management Shell

If you need to enter the MongoDB background management, you can directly execute the MongoDB command file because the MongoDB executable file has been added to the PATH.

MongoDB Shell is MongoDB's own interactive Javascript shell, which is used to operate and manage MongoDB in an interactive environment.

When you enter the mongoDB background, it will link to the test document (database) by default:

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-febhtbhq-1639830975124) (/ home / Lance /. Config / typora / typora user images / image-20211218202923041. PNG)]

MongoDB concept analysis

In mongodb, the basic concepts are document, collection and database. The following table will make it easier for you to understand some of the concepts in Mongo:

SQL terms / conceptsMongoDB terms / conceptsExplanation / explanation
databasedatabasedatabase
tablecollectionDatabase tables / sets
rowdocumentData record line / document
columnfieldData field / field
indexindexIndexes
table joinsTable connection, not supported by MongoDB
primary keyprimary keyPrimary key, MongoDB will automatically_ The id field is set as the primary key

MongoDB create database

database

Multiple databases can be established in one mongodb.

The default database of MongoDB is "db", which is stored in the data directory.

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

The "show dbs" command can display a list of all data.

toby@recsys:~$ mongo
MongoDB shell version: 2.6.10
connecting to: test
> show dbs
admin  (empty)
local  0.078GB

Execute the "db" command to display the current database object or collection.

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

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
> 

grammar

The syntax format of MongoDB database creation is as follows:

use DATABASE_NAME

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

example

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
> 

If you want to view all databases, you can use the show dbs command:

> show dbs
admin  (empty)
local  0.078GB
> 

You can see that the database tobytest we just created is not in the database list. 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
> 

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

Note: in MongoDB, the collection will be created only after the content is inserted! That is, after creating a set (data table), you need to insert another document (record) before the set can be really created.

MongoDB create collection

The createCollection() method is used in MongoDB to create a collection.

Syntax format:

db.createCollection(name, options)

Parameter Description:

  • Name: name of the collection to be created
  • Options: optional parameter that specifies options for memory size and index

options can be the following parameters:

fieldtypedescribe
cappedBoolean(optional) if true, a fixed collection is created. A fixed collection is a collection with a fixed size. When the maximum value is reached, it will automatically overwrite the oldest document. When the value is true, the size parameter must be specified.
autoIndexIdBooleanThis parameter is no longer supported after 3.2. (optional) if true, the index will be automatically created in the _id field. The default is false.
sizenumerical value(optional) specify a maximum number of bytes for the fixed set. If capped is true, you also need to specify this field.
maxnumerical value(optional) specifies the maximum number of documents contained in the fixed collection.

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

example

Create the runoob collection in the tobytest database:

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

If you want to view existing collections, you can use the show collections or show tables command:

> show tables
system.indexes
tobycollection
tobytest
> 

MongoDB delete collection

The drop() method is used in MongoDB to delete the collection.

Syntax format:

db.collection.drop()

Parameter Description:

  • nothing

Return value

If the selected collection is deleted successfully, the drop() method returns true; otherwise, it returns false.

example

In the database tobytest, we can first view the existing collections through the show collections command:

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

Then delete the collection tobycollection:

> db.tobycollection.drop()
true
> 

View the collections in the database tobytest again through show collections:

> show collections
system.indexes
tobytest
> 

As can be seen from the results, the tobycollection collection has been deleted.

MongoDB insert document

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

All data stored in the collection is in BSON format.

BSON is a binary storage format similar to JSON, which is short for Binary JSON.

Insert document

MongoDB uses the insert() or save() method to insert documents into the collection. The syntax is as follows:

db.COLLECTION_NAME.insert(document)
or
db.COLLECTION_NAME.save(document)
  • save(): if_ If the id primary key exists, the data will be updated. If it does not exist, the data will be inserted. This method is obsolete in the new version and can be used dB collection. Insertone() or dB collection. Replaceone() instead.
  • insert(): if the inserted data primary key already exists, it will be deleted springframework. dao. Duplicatekeyexception exception, prompting that the primary key is duplicate and the current data will not be saved.

example

The following documents can be stored in the col collection of the tobytest database of MongoDB:

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

In the above example, col is our collection name. If the collection is not in the database, MongoDB will automatically create the collection and insert the document.

To view inserted documents:

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

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
... })

The results displayed after execution are as follows:

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

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 }
> 

MongoDB update document

MongoDB uses the update() and save() methods to update the documents in the collection. Next, let's take a detailed look at the application of the next two functions and their differences.

update() method

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

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

Parameter Description:

  • Query: query criteria of update, similar to the query criteria after where in sql update query.
  • Update: update object and some Update Operators (such as , , , inc...) can also be understood as the data after the set in the sql update query
  • upsert: optional. This parameter means whether to insert objnew if there is no update record. True means insert. The default is false and not insert.
  • multi: optional. mongodb is false by default. Only the first record found will be updated. If this parameter is true, all the records found by conditions will be updated.
  • writeConcern: optional, the level of exception thrown.

example

We insert the following data into the set col:

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

Next, we update the title through 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
}
> 

You can see that the title is updated from "Toby MongoDB" to "MongoDB".

MongoDB delete document

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

MongoDB data update can use the update() function. It is a good habit to execute the find() command before executing the remove() function to determine whether the execution conditions are correct.

grammar

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

db.collection.remove(
   <query>,
   <justOne>
)

If your MongoDB is later than version 2.6, the syntax format is as follows:

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

Parameter Description:

  • query: (optional) the condition of the deleted document.
  • justOne: (optional) if set to true or 1, only one document will be deleted. If this parameter is not set, or the default value is false, all documents matching the criteria will be deleted.
  • writeConcern: (optional) the level at which the exception was thrown.

example

We performed two inserts for 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 })
> 

Use the find() function 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 }
> 

Next, we remove the document with the title 'Toby MongoDB':

> db.col.remove({'title':'Toby MongoDB'})
WriteResult({ "nRemoved" : 2 }) # Two were deleted
> 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 }
> 

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

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

If you want to delete all data, you can use the following method (similar to the truncate command of conventional SQL):

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

MongoDB query document

MongoDB uses the find() method to query documents.

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)
  • Query: optional. Use the query operator to specify query criteria
  • Projection: optional, use the projection operator to specify the returned key. When querying, all key values in the document are returned. You only need to omit this parameter (omitted by default).

If you need to read data in a readable way, you can use the pretty() method. The syntax format is as follows:

>db.col.find().pretty()

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

example

In the following example, we query the data in the collection 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
}
> 

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

MongoDB AND condition

MongoDB's find() method can pass in multiple keys, AND each key is separated by commas, that is, the AND condition of conventional SQL.

The syntax format is as follows:

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

example

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

> 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
}
> 

The above example is similar to the WHERE statement: WHERE by = 'Toby' AND title='Toby MongoDB '

MongoDB OR condition

The MongoDB OR conditional statement uses the keyword $or. The syntax format is as follows:

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

example

In the following example, we demonstrate how to query a document with a key by value of Toby or a key title Value of 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
}
> 

Combined use of AND and OR

The following example demonstrates the joint use of AND and OR, similar to the conventional SQL statement: '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
}
> 

MongoDB sorting

MongoDB sort() method

In MongoDB, use the sort() method to sort the data. The sort() method can specify the fields to be sorted through parameters, and use 1 and - 1 to specify the sorting method, where 1 is ascending and - 1 is descending.

grammar

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

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

example

The data in col set is as follows:

> 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
}
> 

The following example demonstrates that the data in the col set is arranged in descending order by the field likes:

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

Python MongoDB

PyMongo

Python needs a MongoDB driver to connect to MongoDB. Here we use PyMongo driver to connect.

pip installation

pip is a general Python package management tool, which provides the functions of finding, downloading, installing and uninstalling Python packages.

Install pymongo:

$ python3 -m pip install pymongo

Test PyMongo

Next, we can create a test file demo_test_mongodb.py, the code is as follows:

import pymongo

Execute the above code file. If no error occurs, the installation is successful.

Create database

Create a database

To create a database, you need to use the MongoClient object, and specify the URL address of the connection and the name of the database to be created.

In the following example, we create the database pydb:

example

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

Note: in MongoDB, the database will be created only after the content is inserted! That is, after the database is created, a set (data table) should be created and a document (record) inserted before the database can be really created.

Determine whether the database already exists

We can read all databases in MongoDB and judge whether the specified database exists:

example

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 already exists!")
else:
  print('Database does not exist')

**Note: * * database_names is obsolete in the latest version of Python, Python 3 The version after 7 + is changed to list_database_names().

Create collection

Collections in MongoDB are similar to SQL tables.

Create a collection

MongoDB uses database objects to create collections. Examples are as follows:

example

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

mycol=myclient["col_set"]

Note: in MongoDB, the collection will be created only after the content is inserted! That is, after creating a set (data table), you need to insert another document (record) before the set can be really created.

Determine whether the collection already exists

We can read all sets in MongoDB database and judge whether the specified set exists:

example

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:   # Determine whether the sites collection exists
  print("Collection already exists!")
else:
  print('Collection does not exist')

Python Mongodb insert document

A document in MongoDB is similar to a record in an SQL table.

Insert collection

To insert a document into a collection, use insert_ The first parameter of the one () method is the dictionary name = > value pair.

The following example applies to col_ Insert document in set collection:

example

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)

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG mbqiu1si-1639830975128)( https://i.loli.net/2021/11/02/yY6EmCx4PfLolFQ.png )]

On the command line, see if the insertion was successful

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

Insert multiple documents

Insert multiple documents into the collection using insert_many() method, the first parameter of which is the dictionary list.

example

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)
 
# Output corresponding to all inserted documents_ id value
print(x.inserted_ids)

On the command line, see if the insertion was successful

> 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" }
> 

Python Mongodb query document

Find and find are used in MongoDB_ One method to query the data in the collection, which is similar to the SELECT statement in SQL.

Query a piece of data

We can use find_ The one () method to query a piece of data in the collection.

Query col_ The first data in the set document:

example

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

Query all data in the collection

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

The following example looks for col_ All data in the set:

example

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

Query the data of the specified field

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

example

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)

Query according to specified criteria

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

The following example finds data with the name field "Toby":

example

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)

Returns the specified number of records

If we want to set the specified number of records for the query results, we can use the limit() method, which only accepts a numeric parameter.

The following example returns 3 document records:

example

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

Python Mongodb modify document

We can use update in MongoDB_ The one () method modifies the records in the document. The first parameter of this method is the query condition, and the second parameter is the field to be modified.

If more than one matching data is found, only the first one will be modified.

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

example

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)
 
# Output the modified "sites" collection
for x in mycol.find():
  print(x)

sort

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

The first parameter of sort() method is the field to be sorted, and the second field specifies the sorting rule. 1 is in ascending order, - 1 is in descending order, and the default is in ascending order.

Sort fields in ascending order:

example

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)

Sort fields 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)

Python Mongodb delete data

We can use delete_one() method to delete a document. The first parameter of this method is the query object, specifying which data to delete.

The following example deletes a document whose name field value is "Timi":

example

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

Delete all documents in the collection

delete_ The many() method will delete all documents in the collection if an empty query object is passed in:

example

import pymongo
 
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pydb"]
mycol = mydb["col_set"]
  
x = mycol.delete_many({})
 
print(x.deleted_count, "Documents deleted")

Delete collection

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

The following example deletes col_set set:

example

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

Let's check at the terminal

> use pydb
switched to db pydb
> show tables
system.indexes
> 

Topics: Database MongoDB