Summary of basic operation methods for adding deleting looking and changing documents in MongoDB

  • 2020-05-30 21:14:52
  • OfStack

Insert document: insert() method

To insert data into the MongoDB collection, you need to use MongoDB's insert() or save() methods.

Grammar:

The basic syntax of the insert() command is as follows:


 >db.COLLECTION_NAME.insert(document)

Example:

 >db.mycol.insert({    _id: ObjectId(7df78ad8902c),    title: 'MongoDB Overview',     description: 'MongoDB is no sql database',    by: 'tutorials point',    url: 'https://www.ofstack.com',    tags: ['mongodb', 'database', 'NoSQL'],    likes: 100 })
Here mycol is the name of the collection, as created in the previous tutorial. If the collection does not exist in the database, MongoDB creates the collection and inserts it into the document.

Insert into the document, if we do not specify the _id parameter, then MongoDB this document allocates a unique ObjectId.

_id is a base 106 number of 12 bytes, with each document in 11 collections. The 12 bytes are divided as follows:


 _id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)

To insert multiple documents for a single query, you can pass a file for the array insert() command.

Example:

 >db.post.insert([ {    title: 'MongoDB Overview',     description: 'MongoDB is no sql database',    by: 'tutorials point',    url: 'https://www.ofstack.com',    tags: ['mongodb', 'database', 'NoSQL'],    likes: 100 }, {    title: 'NoSQL Database',     description: 'NoSQL database doesn't have tables',    by: 'tutorials point',    url: 'https://www.ofstack.com',    tags: ['mongodb', 'database', 'NoSQL'],    likes: 20,     comments: [        {          user:'user1',          message: 'My first comment',          dateCreated: new Date(2013,11,10,2,35),          like: 0        }    ] } ])
To insert a file, you can also use db.post.save (document). If you do not specify _id in the document, then make its save() method and insert() method work like 1. If you specify _id, it replaces the entire data file, which contains _id specifying the save() method.


Delete the document: remove() method

The remove() method of MongoDB is used to delete documents from the collection. The remove() method takes two arguments. The first is to delete criteria, and the second is the justOne logo:

(1) deletion criteria :(optional) delete standard, will be deleted according to the file.

(2) justOne: (optional) if set to true or 1, then only 1 file is deleted.

Grammar:

The basic syntax remove() method is as follows


 >db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Example:

Consider the following data mycol collection.

 { "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Yiibai Overview"}
The following example will delete all files with the title 'MongoDB Overview'

 >db.mycol.remove({'title':'MongoDB Overview'}) >db.mycol.find() { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Yiibai Overview"} >
There's only one delete.

If there are multiple records and only the first record is to be deleted, set the justOne parameter in the remove() method


 >db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Delete all files:

If you do not specify a delete condition, MongoDB will then delete the entire file from the collection. This is equivalent to the truncate command for SQL.


 >db.mycol.remove() >db.mycol.find() >


Query documents:
1. find () method
To query the collection data from MongoDB, use the find() method of MongoDB.

Grammar:

The basic find() method syntax is as follows


 >db.COLLECTION_NAME.find()

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

2. pretty () method

The results are displayed in a formatted fashion, using the pretty() method.

Grammar:


 >db.mycol.find().pretty()

Example:

 >db.mycol.find().pretty() {    "_id": ObjectId(7df78ad8902c),    "title": "MongoDB Overview",     "description": "MongoDB is no sql database",    "by": "tutorials point",    "url": "https://www.ofstack.com",    "tags": ["mongodb", "database", "NoSQL"],    "likes": "100" } >
In addition to the find() method, there is an findOne() method that returns a file.

RDBMS Where clause is equivalent to MongoDB.

To query 1 of the file based on some conditions, you can use the following operation

操作 语法 例子 RDBMS 等同
Equality key db.mycol.find({"by":"tutorials point"}).pretty() where by = 'tutorials point'
Less Than {<key>:{$lt:<value>}} db.mycol.find({"likes":{$lt:50}}).pretty() where likes < 50
Less Than Equals {<key>:{$lte:<value>}} db.mycol.find({"likes":{$lte:50}}).pretty() where likes <= 50
Greater Than {<key>:{$gt:<value>}} db.mycol.find({"likes":{$gt:50}}).pretty() where likes > 50
Greater Than Equals {<key>:{$gte:<value>}} db.mycol.find({"likes":{$gte:50}}).pretty() where likes >= 50
Not Equals {<key>:{$ne:<value>}} db.mycol.find({"likes":{$ne:50}}).pretty() where likes != 50

3.AND is used in MongoDB

Grammar:

In the find() method, if the ',' is separated by multiple keys, then MongoDB handles the AND condition. The basic syntax of AND is as follows:


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

example

The example given below shows all tutorials with the title "MongoDB Overview"

 >db.mycol.find({"by":"tutorials point","title": "MongoDB Overview"}).pretty() {    "_id": ObjectId(7df78ad8902c),    "title": "MongoDB Overview",     "description": "MongoDB is no sql database",    "by": "yiibai",    "url": "https://www.ofstack.com",    "tags": ["mongodb", "database", "NoSQL"],    "likes": "100" } >
The example given above corresponds to the where clause 'where by='yiibai AND title='MongoDB Overview', which can be used by any number of key-value pairs in the find clause.

4. OR MongoDB

Grammar:

To query the file based on the OR condition, use the $or keyword. The basic syntax of OR is as follows:


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

example

The example given below shows all tutorials written by 'yiibai' or titled 'MongoDB Overview'

 >db.mycol.find({$or:[{"by":"yiibai"},{"title": "MongoDB Overview"}]}).pretty() {    "_id": ObjectId(7df78ad8902c),    "title": "MongoDB Overview",     "description": "MongoDB is no sql database",    "by": "yiibai",    "url": "https://www.ofstack.com",    "tags": ["mongodb", "database", "NoSQL"],    "likes": "100" } >
5.AND and OR 1 in use

example

The example given below shows an image of a file larger than 100, with the title "MongoDB Overview" or "yiibai". Is equivalent to SQL where clause


'where likes>10 AND (by = 'yiibai' OR title = 'MongoDB Overview')'

 >db.mycol.find("likes": {$gt:10}, $or: [{"by": "yiibai"}, {"title": "MongoDB Overview"}] }).pretty() {    "_id": ObjectId(7df78ad8902c),    "title": "MongoDB Overview",     "description": "MongoDB is no sql database",    "by": "yiibai",    "url": "https://www.ofstack.com",    "tags": ["mongodb", "database", "NoSQL"],    "likes": "100" } >

Update the document
The update() and save() methods of MongoDB are used to update the collection of documents. The update() method updates the existing document value and replaces the save() method in the existing document passed file.

1. MongoDB Update () method

The update() method updates the existing document value.

Grammar:

The basic syntax for the update() method is as follows


 _id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
0

example

Consider the following data mycol collection.

 { "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
The following example will set the file with the new title 'MongoDB Overview' and update it with the title 'New MongoDB Tutorial'

 >db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}}) >db.mycol.find() { "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Yiibai Overview"} >
By default, MongoDB will only update single 1 files to update multiple files you need to set the parameter 'multi' to true

 >db.post.insert([ {    title: 'MongoDB Overview',     description: 'MongoDB is no sql database',    by: 'tutorials point',    url: 'https://www.ofstack.com',    tags: ['mongodb', 'database', 'NoSQL'],    likes: 100 }, {    title: 'NoSQL Database',     description: 'NoSQL database doesn't have tables',    by: 'tutorials point',    url: 'https://www.ofstack.com',    tags: ['mongodb', 'database', 'NoSQL'],    likes: 20,     comments: [        {          user:'user1',          message: 'My first comment',          dateCreated: new Date(2013,11,10,2,35),          like: 0        }    ] } ])
0 2. MongoDB Save () method

The save() method replaces the existing document with the save() method through the new document

grammar

The basic syntax of the save() method for MongoDB is as follows:


 _id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
1

example

The following example will replace the file with _id for '5983548781331 adf45ec7'

 >db.mycol.save(    {       "_id" : ObjectId(5983548781331adf45ec7), "title":"Yiibai New Topic", "by":"Yiibai"    } ) >db.mycol.find() { "_id" : ObjectId(5983548781331adf45ec5), "title":"Yiibai New Topic", "by":"Yiibai"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Yiibai Overview"} >



Related articles: