First, insert the document
Using the Insert method to insert a document into a collection, there are several ways to create a collection if the collection does not exist:
- Db.collection.insertOne ({}): (v3.2 new) #插入一个文档到集合中
> Db.users.insertOne (... {... Name: "Marry",... age:26,... Status: "Pending" ...} ... ) { "acknowledged": true, "Insertedid": ObjectId ("565d23db556b61b96bdb1b20")}
- Db.collection.insertMany ([{},{} ...]) (v3.2 new) #插入多个文档
> Db.users.insertMany (... [... {Name: "Sue", Age:25,status: "Pending"},... {Name: "Bob", Age:24,status: "Enrolled"},... {name: "Ann", Age:28,status: "Enrolled"} ...] ... ) { "acknowledged": true, "Insertedids": [ ObjectId ("565d2d75556b61b96bdb1b21"), ObjectId (" 565d2d75556b61b96bdb1b22 "), ObjectId (" 565d2d75556b61b96bdb1b23 ") ]}
- Insert () #既能插入一个文档, or multiple documents can be inserted
> post={"title": "My First Blog", "Author": "Darren", "Content": "This is My first blog"} { "title": "My First blog",
"Author": "Darren", " content": "This is my first blog"}> Db.posts.insert (POST) Writeresult ({"ninserted": 1})
> Db.users.insert (
... [
... {Name: "Test1", Age:20,status: "Pending"},
... {Name: "Test2", Age:21,status: "Enrolled"}
... ]
... )
Bulkwriteresult ({
"Writeerrors": [],
"Writeconcernerrors": [],
"Ninserted": 2,
"nupserted": 0,
"nmatched": 0,
"Nmodified": 0,
"Nremoved": 0,
"upserted": []
})
Second, query the document
1, Db.collection.find (query,projection)
Parameter description:
Parameter type description
Query document optional, returns the documents for the specified condition, if all documents are queried ({})
Projection document optional, returns the specified field, and 1 indicates that true,0 represents false
In the query parameter, you can specify an operator, such as greater than, less than, and so on.
{<field>: {$eq: <value>}}
Example Description:
- Querying all documents in a collection
> Db.a.find ({})
- Querying documents that match a condition, such as _id=5
> Db.a.find ({_id:5}) {"_id": 5, "name": {"First": "Ole-johan", "Last": "Dahl"}, "Birth": Isodate ("1931-10-12t04: 00:00z ")," Death ": Isodate (" 2002-06-29t04:00:00z ")," contribs ": [" OOP "," Simula "]," awards ": [{" award ":" Rosing Pr Ize ', ' Year ': 1999, ' by ': ' Norwegian Data Association '}, {' Award ': ' Turing Award ', ' Year ': 2001, ' by ': ' ACM '}, {" Award ":" IEEE John von Neumann Medal "," Year ": 2001," by ":" IEEE "}]}> Db.a.find ({_id:{$eq: 5}}) #通过操作符的方式 {" _i D ": 5," name ": {" First ":" Ole-johan "," Last ":" Dahl "}," Birth ": Isodate (" 1931-10-12t04:00:00z ")," Death ": Isodate ( "2002-06-29t04:00:00z"), "contribs": ["OOP", "Simula"], "awards": [{"award": "Rosing Prize", "Year": 1999, "by": "Norwegian Data Association"}, {"award": "Turing Award", "Year": 2001, "by": "ACM"}, {"award": "IEEE John von Neum Ann Medal "," Year ": 2001," by ":" IEEE "}]}
- Querying the document and returning the specified field
> Db.a.find ({_id:{$eq: 5}},{name:1,first:1,last:1}) #返回name, first,last three fields, return _id{"_id" By default: 5, "name": {"First": "Ol" E-johan "," Last ":" Dahl "}}> db.a.find ({_id:{$eq: 5}},{name:1,first:1,last:1,_id:0}) #指定_id不显示 {" name ": {" First ":" Ole-johan "," Last ":" Dahl "}}
#查询_id大于1, documents less than 3 > db.a.find ({_id:{$gt: 1, $lt: 5}},{name:1,first:1,last:1}) {"_id": 3, "name": {"First": "Grace" "," Last ":" Hopper "}} {" _id ": 4," name ": {" First ":" Kristen "," Last ":" Nygaard "}}
There is much more to the query criteria and operators, please refer to the official documentation for more details.
Third, update the document
MongoDB provides several ways to update a document:
- Db.collection.updateOne (filter,update,options) Update a document
Parameter type description
Filter document is the same as a query, when {} is empty, only the first document of the collection is updated
Update document updates, which can be updated with the update operator, such as $set, $unset, $rename
Upsert Boolean optional, when True, inserts a new document if no updated document is found
Example:
> Db.a.updateone (... {_id:5},... {$set: {year:2000}} # $set operator indicates the value of the updated field ...) {"acknowledged": true, "Matchedcount": 1, "Modifiedcount": 1}> db.a.find ({_id:5},{year:1}) {"_id": 5, "Year":
#}
- Db.collection.updateMany ()
> Db.a.updatemany (... {_id: {$lt: 5}},... {$set: {year:1999}} ...) {"acknowledged": true, "Matchedcount": 3, "Modifiedcount": 3}> db.a.find ({_id:{$lt: 5}},{year:1}) {"_id": 1, "year ": 1999} {" _id ": 3," Year ": 1999} {" _id ": 4," Year ": 1999}
- Db.collection.replaceOne (): You do not need the same field as the current field as many, can be arbitrarily substituted.
> Db.a.replaceone (... {_id:5},... {Name: "Darren", Address: "1022", year:1988} ...) {"acknowledged": true, "Matchedcount": 1, "Modifiedcount": 1}> db.a.find ({_id:5}) {"_id": 5, "name": "Darren", " Address ":" 1022 "," Year ": 1988}
- Db.collection.update (): You can update one or more documents and, of course, replace a document
Db.users.update ( {age: {$gt:}}, {$set: {status: "A"}}, {multi:true})
Iv. Deleting documents
Db.xxx.remove ({}): Delete all documents in the XXX collection, but do not delete the collection itself and index, remove must take the filter parameter, empty {} means delete all.
Note: Deleting data is permanent, cannot be recovered, and cannot be undone.
When the amount of database in the collection is very large, removing with remove is sometimes slow, and drop () can provide a good speed, but it will delete all the collections and indexes.
In addition to the Remove method, the new version provides the following methods for deletion:
- Db.collection.deleteOne ()
You can delete the first one of the matching documents with the filter parameters, and delete the first one if you do not add any filtering criteria.
Db.users.deleteOne ( {status: "Reject"})
- Db.collection.deleteMany ()
Db.users.deleteMany ( {status: "Reject"})
In addition MongoDB also provides a large kill device, you can put insert,update,delete together in batch execution:
Db.collection.bulkWrite ()
Db.collection.bulkWrite ( [ {insertone: {"Document": {name: "Sue", Age:26}}}, {insertone: {"Docum Ent ": {name:" Joe ", Age:24}}, {insertone: {" Document ": {name:" Ann ", Age:25}}, {insertone: {"Document": {Name: "Bob", Age:27}}, {updatemany: { "filter": {age: {$gt: +}}, "Update": { $set: {"status": "Enrolled"}}}} , {deletemany: {"filter": {"status": {$exists: true}}}}
])
Curd operation of the "three" MongoDB document