The first chapter the INSERT
- If a document fails to be inserted during the insert process, all documents before it succeed, including all subsequent documents fail.
- Mongodb only performs basic checks. A maximum of 16MB is required. It is easy to insert illegal data. So it’s only open to trusted applications.
- Mainstream language driver, data insertion time to do verification. Such as whether the document is too large, whether the document contains strings other than UTF8, and whether it uses unrecognized types.
Db.collection.insert () inserts one or more documents into the collection
Insert ({name:'frist doc',age:'1',tag:'frist insert doc'}) WriteResult({"nInserted" : 1}) multiple operations: Db.ins. insert([{name:' SEC doc',age:'2',tag:' SEC insert doc'}, {name:' THR doc',age:'3',tag:' THR insert doc'}]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })Copy the code
2. The db. Collection. InsertOne () to insert a new document in the collection.
Db.ins. insertOne({name:'four doc',age:'4',tag:'four insert doc'}) {" indispensable ": true, "insertedId" : ObjectId("5c85f85806bbda89cc0dc44a") }Copy the code
3. The db. Collection. InsertMany () more than insert a new document in the collection.
Db.ins. insertMany([{name:'five doc',age:'5',tag:'five insert doc'}, {name:'six doc',age:'7',tag:'six insert doc'}, {name:'seven doc',age:'8',tag:'seven insert doc'}]) {" indispensable ": true, "insertedIds" : [ ObjectId("5c85f93806bbda89cc0dc44b"), ObjectId("5c85f93806bbda89cc0dc44c"), ObjectId("5c85f93806bbda89cc0dc44d") ] }Copy the code
4. Perform other operations that can be inserted
Db.collection.update () with upsert true db.collection.updateOne() with upsert true db.collection.updatemany () with upsert true db.collection.updatemany () When the upsert is true / / db. The third parameter collection. The findAndModify () when the upsert is true * * db in the collection. The findAndModify () when the upsert is true * * Db. Collection. FindOneAndReplace () when the upsert is true
The second chapter the UPDATE
- $set new keys and update keys
- $unset the delete key
- The value of the $INCr key can be increased or decreased. The value of the key can only be a number. The key type can only be an integer, a long integer, or a double precision floating point.
- $push adds elements to the end of the array
1. Db.collection. update Updates records
Insert test data
Db.inventory.insertmany ([{item: "canvas", qty: 100, size: {h: 28, w: 35.5, uom: "cm"}, status: "A"}, {item: "Journal ", Qty: 25, size: {h: 14, W: 21, UOM: "cm"}, status: "A"}, {item: "mat", Qty: 85, size: {h: 27.9, w: 35.5, UOM: "CM"}, status: "A"}, {item: "mousepad", Qty: 25, size: {h: 19, w: 22.85, UOM: "cm"}, status: "P"}, {item: "notebook", qty: 50, size: {h: 8.5, w: 11, uom: "in"}, status: "P"}, {item: "paper", qty: 100, size: {h: 8.5, w: 11, uom: "in"}, status: a "D"}, {item: "planner", qty: 75, size: {h: 22.85, w: 30, uom: "cm"}, the status: "D"}, {item: "Postcard ", Qty: 45, size: {H: 10, W: 15.25, UOM:" CM "}, status: "A"}, {item: "Sketchbook ", qty: 80, size: {h: 14, W: 21, UOM: "CM"}, status: "A"}, {item: "Sketch pad", QTY: 95, size: {h: 22.85, W: 30.5, UOM: "cm" }, status: "A" } ]); { "acknowledged" : true, "insertedIds" : [ ObjectId("5cbd706b35bc4d3801a312d1"), ObjectId("5cbd706b35bc4d3801a312d2"), ObjectId("5cbd706b35bc4d3801a312d3"), ObjectId("5cbd706b35bc4d3801a312d4"), ObjectId("5cbd706b35bc4d3801a312d5"), ObjectId("5cbd706b35bc4d3801a312d6"), ObjectId("5cbd706b35bc4d3801a312d7"), ObjectId("5cbd706b35bc4d3801a312d8"), ObjectId("5cbd706b35bc4d3801a312d9"), ObjectId("5cbd706b35bc4d3801a312da") ] }Copy the code
2. Db. Collections. UpdateOne () to update the first qualified documents
Db.inventore. find({item:"paper"}) {"_id" : ObjectId(" 5c85fCD906bbDA89CC0dc450 "), "item" :"paper", "qty" : 100, "size" : {" h ": 8.5," w ": 11," uom ":" in "}, "status" : "D"} {" _id ": ObjectId(" 5C861B4B274C7C6EFF9c0106 "), "item" : "paper", "qTY" : 100, "size" : {" H ": 8.5, "w" : 11, "uom" : Db.inventory. updateOne({item: "paper"}, {$set: {"size. Uom ": {$set: {"size. {"matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : Find ({item:"paper"}) {"_id" : ObjectId(" 5c85fCD906bbDA89CC0dc450 "), "item" : "Paper", "qty" : 100, the "size" : {" h ": 8.5," w ": 11," uom ":" cm "}, "status" : "P", "lastModified" : ISODate(" 2019-03-11t08:38:32.820z ")} {"_id" : ObjectId(" 5C861b4b274C7c6eff9c0106 "), "item" : "paper", "qty" : 100, "size" : {" h ": 8.5," w ": 11," uom ":" in "}, "status" : "D"}Copy the code
3. The db. Collection. UpdateMany () more than update document, if the upsert to true. If no document is saved, the document is inserted.
Db.inventory. find({qty:{$lt:50}}) {"_id" : ObjectId(" 5c85fCD906bbDA89CC0dc44e "), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" } { "_id" : ObjectId(" 5C85FCD906BBDA89CC0DC452 "), "item" : "Postcard "," QTY ": 45, "size" : {" H" : 10, "w" : 15.25, "Uom" : "cm" }, "status" : "A" } { "_id" : ObjectId("5c861b4b274c7c6eff9c0102"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" } { "_id" : ObjectId("5c861b4b274c7c6eff9c0104"), "item" : "Mousepad," "qty" : 25, "size" : {" h ": 19" w ": 22.85," uom ":" cm "}, "status" : "P"} {" _id ": ObjectId(" 5C861B4B274C7C6EFF9C0108 "), "item" : "Postcard "," QTY ": 45, "size" : {" H" : 10, "w" : 15.25, "Uom" : Db.inventory. updateMany({"qty": {$lt: 50}}, {$set: {" sie.uom ": "in", status: {$set: {" sie.uom ": "in", status: {"matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : "matchedCount" : Find ({qty:{$lt:50}}) {"_id" : ObjectId(" 5c85fCD906bbDA89CC0dc44e "), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "in" }, "status" : "P", "lastModified" : ISODate(" 2019-03-11T08:41:16.569z ")} {"_id" : ObjectId(" 5C85fCD906bbDA89CC0DC452 "), "item" : "Postcard "," Qty ": 45, "size" : {" h ": 10," w ": 15.25," uom ":" in "}, "status" : "P", "lastModified" : ISODate(" 2019-03-11t08:41:16.570z ")} {"_id" : ObjectId(" 5C861b4b274C7c6eff9c0102 ", "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "in" }, "status" : "P", "lastModified" : ISODate(" 2019-03-11t08:41:16.570z ")} {"_id" : ObjectId(" 5C861b4b274C7c6eff9c0104 "), "item" : 25, "size" : {" h ": 19" w ": 22.85," uom ":" in "}, "status" : "P", "lastModified" : ISODate(" 2019-03-11T08:41:16.570z ")} {"_id" : ObjectId(" 5C861B4B274C7C6EFF9c0108 "), "item" : "Postcard ", "qty" : 45, "size" : {" h ": 10," w ": 15.25," uom ":" in "}, "status" : "P", "lastModified" : ISODate (" the 2019-03-11 T08: shalt. 570 z ")}Copy the code
4. Db.collection.replaceone () replaces the first qualifying document and passes the new parameter to replaceOne. The ID field cannot be replaced.
Db.inventore. find({item:"paper"}) {"_id" : ObjectId(" 5c85fCD906bbDA89CC0dc450 "), "item" :"paper", "qty" : 100, "size" : {" h ": 8.5," w ": 11," uom ":" cm "}, "status" : "P", "lastModified" : ISODate(" 2019-03-11t08:38:32.820z ")} {"_id" : ObjectId(" 5C861b4b274C7c6eff9c0106 "), "item" : "paper", "qty" : 100, "size" : {"h" : 8.5, "w" : 11, "UOM" : "in"}, "status" : "D"} Execute update command db.inventory.replaceOne({item: "paper" }, { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: {" indispensable ": true, "matchedCount" : 1, "modifiedCount" : 1}}) {" indispensable" : true, "matchedCount" : 1, "modifiedCount" : Db.invento.find ({item:"paper"}) {"_id" : ObjectId(" 5c85fCD906bbDA89CC0dc450 "), "item" :"paper", "instock" : [ { "warehouse" : "A", "qty" : 60 }, { "warehouse" : "B", "qty" : 40 } ] } { "_id" : ObjectId(" 5C861B4B274C7C6EFF9c0106 "), "item" : "paper", "qTY" : 100, "size" : {" H ": 8.5, "w" : 11, "uom" : Db.test.find () {"_id" : ObjectId(" 5FD07c9198ada1CE0d1e52a5 "), "name" : ObjectId(" 5FD07c9198ada1ce0d1e52a5 ") "joe", "friends" : 32, "enemies" : 2 } db.test.replaceOne( {'name':'joe'}, {'name':'joe','relationships':{"friends" : 32,"enemies" : 2}} ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } db.test.find() { "_id" : ObjectId("5fd07c9198ada1ce0d1e52a5"), "name" : "joe", "relationships" : { "friends" : 32, "enemies" : 2}} bill - repli: PRIMARY > db. Collections. UpdateONE, updateMany, updateReplace when upsert is true, if the record does not exist the insert new record try { db.inventory.updateOne( { "name" : "Pizza Rat's Pizzaria" }, { $set: {"_id" : 4, "violations" : 7, "borough" : "Manhattan" } }, { upsert: true } ); } catch (e) { print(e); } result: Because there is no condition to match this record. So a new record is inserted. { "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0, "upsertedId" : 4 } { "_id" : 4, "name" : "Pizza Rat's Pizzaria", "borough" : "Manhattan", "violations" : 7 } db.blog.find() { "_id" : ObjectId("5fc5a6a3e78f91ca2839cb16"), "name" : "a" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb17"), "name" : "b" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb18"), "name" : "c" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb19"), "name" : "d" }Copy the code
5. Add/update field SET and delete field unset
Db.blog. update({},{$set:{'num':''}}) WriteResult({"nMatched" : 1, "nUpserted" : 0, "nModified" : 0) 1 }) db.blog.find() { "_id" : ObjectId("5fc5a6a3e78f91ca2839cb16"), "name" : "a", "num" : "" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb17"), "name" : "b" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb18"), "name" : "c" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb19"), "name" : Db.blog. update({'name':'c'},{$set:{'num':'2'}}) WriteResult({"nMatched" : 1, "nUpserted") : 0, "nModified" : 1 }) db.blog.find() { "_id" : ObjectId("5fc5a6a3e78f91ca2839cb16"), "name" : "a", "num" : "" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb17"), "name" : "b" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb18"), "name" : "c", "num" : "2" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb19"), "name" : Db.blog. update({},{$set:{'num':''}},{multi:1}) WriteResult({"nMatched" : 4, "nUpserted" : 0, "nModified" : 3 }) db.blog.find() { "_id" : ObjectId("5fc5a6a3e78f91ca2839cb16"), "name" : "a", "num" : "" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb17"), "name" : "b", "num" : "" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb18"), "name" : "c", "num" : "" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb19"), "name" : "d", "num" : ""} add conditions for name: c, delete a field when the blog. Update ({' name ':' c '}, {$unset: {' num ':'}}) WriteResult ({" nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) db.blog.find() { "_id" : ObjectId("5fc5a6a3e78f91ca2839cb16"), "name" : "a", "num" : "" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb17"), "name" : "b", "num" : "" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb18"), "name" : "c" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb19"), "name" : "D ", "num" : ""} Delete the first record without conditions. db.blog.update({},{$unset:{'num':''}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) db.blog.find() { "_id" : ObjectId("5fc5a6a3e78f91ca2839cb16"), "name" : "a" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb17"), "name" : "b", "num" : "" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb18"), "name" : "c" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb19"), "name" : "D ", "num" : ""} delete all existing files without condition. db.blog.update({},{$unset:{'num':''}},{multi:1}) WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 2 }) db.blog.find() { "_id" : ObjectId("5fc5a6a3e78f91ca2839cb16"), "name" : "a" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb17"), "name" : "b" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb18"), "name" : "c" } { "_id" : ObjectId("5fc5a6c3e78f91ca2839cb19"), "name" : Insert (post) WriteResult({"nInserted" : 1}) db.blog.find() {"_id" : ObjectId("5fc4ba63bad2853e0468a3c8"), "title" : "My Blog Post", "connect" : "Here is my blog post.", "date" : Pretty () {"_id" : ISODate(" 2020-11-30T9:24:41.117z ")} add a comment to db.blog.find(). Pretty () {"_id" : ObjectId("5fc5a524e78f91ca2839cb15"), "title" : "My Blog Post", "connect" : "Here is my blog post.", "date" : [] db.blog.update({'title':'My blog Post'}, Post) WriteResult({'title':'My blog Post'}) "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) db.blog.find().pretty() { "_id" : ObjectId("5fc5a524e78f91ca2839cb15"), "title" : "My Blog Post", "connect" : "Here is my blog post.", "date" : ISODate(" 2020-12-01T02:06:19.189z "), "Comments" : []}Copy the code
6.$INCR increases and decreases
Update ({"game" : "pinball", "user" : "Joe "},{$inc:{'score':50}}) WriteResult({"nMatched" : 1, "nUpserted" : 0, "nModified" : 1}) because there is no score Db.games.find () {"_id" : ObjectId(" 5FD08A299EF0890CE971e161 "), "game" : "pinball", "user" : "Joe ", "score" : 50} Now score increases by 10000 db.games.update({"game" : "pinball", "user" : "joe"},{$inc:{'score':10000}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : Find () {"_id" : ObjectId(" 5fd08a299EF0890CE971e161 "), "game" : "pinball", "user" : "Joe ", "score" : 10050} Now score minus 5000 db.games.update({"game" : "pinball", "user" : "joe"},{$inc:{'score':-5000}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : Find () {"_id" : ObjectId(" 5fd08a299EF0890CE971e161 "), "game" : "pinball", "user" : "joe", "score" : 5050 }Copy the code
7. Array push,pull,pop,$(subscript)
A list that can be referenced by index and can also be used as a data set
$push adds an element to the end of the array. If the array does not exist, create a new array db.games.find() {"_id" : ObjectId(" 5FD08A299EF0890CE971e161 "), "game" : "pinball", "user" : "joe", "score" : 5050, "comments" : [ { "content" : "very good", "email" : "[email protected]" }, { "content" : "very nice", "email" : "[email protected]" }, 123, 456, 789, { "content" : "very bad", "eamil" : "[email protected]" }, { "content" : "very not nice", "email" : "[email protected]" } ] } db.games.find().pretty() { "_id" : ObjectId("5fd08a299ef0890ce971e161"), "game" : "pinball", "user" : "joe", "score" : 5050, "comments" : [ { "content" : "very good", "email" : "[email protected]" }, { "content" : "very nice", "email" : "[email protected]" }, 123, 456, 789, { "content" : "very bad", "eamil" : "[email protected]" }, { "content" : "very not nice", "email" : Db.game.deleteone ({' Comments ':123}) {" indispensable ": true, "deletedCount" : 0} Use $pull to remove the specified array element. Db.games. update({},{$pull:{'comments':123}}) WriteResult({"nMatched" :1, "nUpserted" :1) 0, "nModified" : 1 }) db.games.update( {}, {$pull:{'comments':456}} ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) db.games.update( {}, {$pull:{'comments':789}} ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) db.games.find().pretty() { "_id" : ObjectId("5fd08a299ef0890ce971e161"), "game" : "pinball", "user" : "joe", "score" : 5050, "comments" : [ { "content" : "very good", "email" : "[email protected]" }, { "content" : "very nice", "email" : "[email protected]" }, { "content" : "very bad", "eamil" : "[email protected]" }, { "content" : "very not nice", "email" : Update ({},{$pop:{'comments':-1}}) WriteResult({"nMatched" : 1, "nUpserted" : 0, "nModified" : Update ({},{$pop:{'comments':1}}) WriteResult({"nMatched" :1, "nUpserted" :1) 0, "nModified" : 1 }) db.games.find().pretty() { "_id" : ObjectId("5fd08a299ef0890ce971e161"), "game" : "pinball", "user" : "joe", "score" : 5050, "comments" : [ { "content" : "very nice", "email" : "[email protected]" }, { "content" : "very bad", "eamil" : "[email protected]" } ] } db.games.update( {"score" : 5050}, {$push: {' top 10 ': {$each:,7,8,9,10,11,12,13,14,15,16,17,18 [6]}}}) WriteResult ({" nMatched ": 1," nUpserted ": 0, "nModified" : 1 }) db.games.find().pretty() { "_id" : ObjectId("5fd08a299ef0890ce971e161"), "game" : "pinball", "user" : "joe", "score" : 5050, "comments" : [ { "content" : "very nice", "email" : "[email protected]" }, { "content" : "very bad", "eamil" : "[email protected]" } ], "top10" : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25]} To limit the number of elements, use $push and $slice together. Slice must be a negative integer to ensure that the specified length is not exceeded. Although I pushed 26 to 33 8 elements. But only the last five elements remain. Use $sort when you can clean up again. Adding data requires cleaning up. db.games.update( {"score" : 5050}, {$push: {' top 10 ': {$each:,27,28,29,30,31,32,33 [26], $slice: - 5}}}) WriteResult ({" nMatched ": 1," nUpserted ": 0, "nModified" : 1 }) db.games.find().pretty() { "_id" : ObjectId("5fd08a299ef0890ce971e161"), "game" : "pinball", "user" : "joe", "score" : 5050, "comments" : [ { "content" : "very nice", "email" : "[email protected]" }, { "content" : "very bad", "eamil" : "[email protected]" } ], "top10" : [29, 30, 31, 32, 33]} Only part of the array can be modified by subscripting the email. Def db.games.update({'game':'pinball'},{$set:{'comments.0. Email ':'[email protected]'}}) WriteResult({"nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) db.games.find().pretty() { "_id" : ObjectId("5fd08a299ef0890ce971e161"), "game" : "pinball", "user" : "joe", "score" : 5050, "comments" : [ { "content" : "very nice", "email" : "[email protected]" }, { "content" : "very bad", "eamil" : "[email protected]" } ], "top10" : [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]} Modify values by subscript. You can use the $sign instead of the subscript. Because sometimes only a query can determine the subscript. Use $to omit the subscript address. Update ({'comments.content':'very nice'},{$set:{'comments.$. Content ':'double very nice'}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) db.games.find().pretty() { "_id" : ObjectId("5fd08a299ef0890ce971e161"), "game" : "pinball", "user" : "joe", "score" : 5050, "comments" : [ { "content" : "double very nice", "email" : "[email protected]" }, { "content" : "very bad", "eamil" : "[email protected]" } ], "top10" : [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]}Copy the code
8. Upsert Updates when the upsert update record exists. Insert a new record when the upsert update record does not exist.
db.email.update({'name':'upsert'}, ... {$set:{'name':'upsert',email:'[email protected]'}} ... ) WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 }) db.email.find().pretty() { "_id" : ObjectId("5fd09fb79ef0890ce971e166"), "name" : "abc", "email" : "[email protected]" } { "_id" : ObjectId("5fd09fb79ef0890ce971e167"), "name" : "def", "email" : "[email protected]" } { "_id" : ObjectId("5fd09fb79ef0890ce971e168"), "name" : "ghi", "email" : "[email protected]" } db.email.update({'name':'upsert'}, {$set:{'name':'upsert',email:'[email protected]'}},true ) WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : ObjectId("5fd718a37de2d14d3a30c553") }) db.email.find().pretty() { "_id" : ObjectId("5fd09fb79ef0890ce971e166"), "name" : "abc", "email" : "[email protected]" } { "_id" : ObjectId("5fd09fb79ef0890ce971e167"), "name" : "def", "email" : "[email protected]" } { "_id" : ObjectId("5fd09fb79ef0890ce971e168"), "name" : "ghi", "email" : "[email protected]" } { "_id" : ObjectId("5fd718a37de2d14d3a30c553"), "name" : "upsert", "email" : "[email protected]"} $setOneInsert Creates and assigns a field to a document, but the field value does not change in subsequent updates.Copy the code
The third chapter the DELETE
1. The db. Collections. DeleteOne delete qualified first document ()
Db.inventory. deleteOne({status: "D"}) {" indispensable ": true, "deletedCount" : 1} A record was deletedCopy the code
2. Db. Collection. DeleteOne () to delete all conform to the conditions of the document
Db.inventory. deleteMany({status: "A"}) {" indispensable ": true, "deletedCount" : 7} Prompt to delete 7 recordsCopy the code
3. You can also run the delete command
Db. Collection. FindOneAndDelete () sorting options. This option allows you to delete the first document sorted in the specified order. Db. Collection. FindAndModify () sorting options. This option allows you to delete the first document sorted in the specified order. Example: db. Ins. FindAndModify ({query: {' age ', '9'}, remove: true})Copy the code
Db.col.drop () drops a collection
Quickly delete all records.Copy the code
The fourth chapter the FIND
- The value must be constant for the document to be queried
1. Db.collection.find ()/db.collection.find({}) Queries all records
Select * from table db.invento.find () {"_id" : ObjectId(" 5C85fCD906bbDA89CC0dc44e "), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" } { "_id" : ObjectId(" 5C85fCD906bbDA89CC0DC44F "), "item" : "notebook", "qTY" : 50, "size" : {" H ": 8.5, "w" : 11, "uom" : "in" }, "status" : "A" } { "_id" : ObjectId("5c85fcd906bbda89cc0dc450"), "item" : "paper", "qty" : 100, "size" : {" h ": 8.5," w ": 11," uom ":" in "}, "status" : "D"} db. The inventory. The find ({}) {" _id ": ObjectId("5c85fcd906bbda89cc0dc44e"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" } { "_id" : ObjectId("5c85fcd906bbda89cc0dc44f"), "item" : "notebook", "qty" : 50, "size" : {" h ": 8.5," w ": 11," uom ":" in "}, "status" : "A"} {" _id ": ObjectId (" 5 c85fcd906bbda89cc0dc450"), "item" : "Paper", "qty" : 100, the "size" : {" h ": 8.5," w ": 11," uom ":" in "}, "status" : "D"}Copy the code
Db.inventory. find({status: “D”}
SELECT * FROM inventory WHERE status = "D" db.inventory.find({status: "D"}) {" _id ": ObjectId (" 5 c85fcd906bbda89cc0dc450"), "item" : "paper", "qty" : 100, the "size" : {" h ": 8.5," w ": 11," uom ": "in" }, "status" : "D" } { "_id" : ObjectId("5c85fcd906bbda89cc0dc451"), "item" : "planner", "qty" : 75, "size" : {" h ": 22.85," w ": 30," uom ":" cm "}, "status" : "D"}Copy the code
3. IN the query
Db.inventory. find({status: {$in: ["A", "D"]}}) MYSQL > inventory SELECT * FROM inventory WHERE status in ("A", "D") However, the official recommendation is to use in to query. db.inventory.find( { status: { $in: [ "A", "D" ] } } ) { "_id" : ObjectId("5c85fcd906bbda89cc0dc44e"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" } { "_id" : ObjectId(" 5C85fCD906bbDA89CC0DC44F "), "item" : "notebook", "qTY" : 50, "size" : {" H ": 8.5, "w" : 11, "uom" : "in" }, "status" : "A" } { "_id" : ObjectId("5c85fcd906bbda89cc0dc450"), "item" : "paper", "qty" : 100, "size" : {" h ": 8.5," w ": 11," uom ":" in "}, "status" : "D"}Copy the code
4. The AND query
The db. The inventory. The find ({status: "A", qty: {$lt: 30}}) and operation. Find documents where status is equal to A and QTY is less than 30. Select * from inventory WHERE status="A" and qty<30 db.inventory.find({status:"A",qty:{$lt:30}}) {"_id" : ObjectId("5c85fcd906bbda89cc0dc44e"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }Copy the code
5. The OR query
Db.inventory. find({$or:[{status:"A"},{qty:{$lt:30}}]}) SELECT * FROM inventory WHERE ($or:[{status:"A"},{$lt:30}}]} status = "A" OR qty < 30 db.inventory.find({$or:[{status:"A"},{qty:{$lt:30}}]}) { "_id" : ObjectId("5c85fcd906bbda89cc0dc44e"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" } { "_id" : ObjectId("5c85fcd906bbda89cc0dc44f"), "item" : "notebook", "qty" : 50, "size" : {" h ": 8.5," w ": 11," uom ":" in "}, "status" : "A"}Copy the code
6.SORT /Pretty /Limit /Skip to return the rest of the document
Db.inventory.find ().sort({name:1}).pretty() sort the name field and beautify the output. db.ins.find().sort({name:1}).pretty() { "_id" : ObjectId("5c85f93806bbda89cc0dc44b"), "name" : "five doc", "age" : "5", "tag" : "five insert doc" } { "_id" : ObjectId("5c85f85806bbda89cc0dc44a"), "name" : "four doc", "age" : "4", "tag" : "four insert doc" } { "_id" : ObjectId("5c85f7ad06bbda89cc0dc447"), "name" : "frist doc", "age" : Db.email.count () 5 Limit () db.email.find().limit(2) {"_id" : ObjectId("5fd09fb79ef0890ce971e166"), "name" : "abc", "email" : "[email protected]" } { "_id" : ObjectId(" 5fd09fb79EF0890ce971e167 "), "name" : "def", "email" : "[email protected]"} Skip the first two results and return the remaining results. db.email.find().skip(2) { "_id" : ObjectId("5fd09fb79ef0890ce971e168"), "name" : "ghi", "email" : "[email protected]" } { "_id" : ObjectId("5fd718a37de2d14d3a30c553"), "name" : "up", "email": "[email protected]" } { "_id" : ObjectId("5fd71a2a2f1e32c5f863d32b"), "name" : "abc", "email" : "[email protected]" }Copy the code
7. Query array documents
Db.ins. insert({"name" : "11.sz", "age" : "11", "tags":["java","kpop","china"]}) db.ins.insert({name:'12',age:12,tags:[{'code':'java','music':'kpop'}]}) db.ins.find({"tags.code":'java'}).pretty() { "_id" : ObjectId("5ee739cb2d413b0b41df886e"), "name" : "12", "age" : 12, "tags" : [ { "code" : "java", "music" : "kpop" } ] } db.ins.find({"tags":'java'}).pretty() { "_id" : ObjectId("5ee736c62d413b0b41df886d"), "name" : "11.sz", "age" : "11", "tags" : [" Java ", "kpop", "China"]} the users. The find ({tags: [" Java "]}) exact match array document, Db.users.find ({tags:[" Java ","mongodb"]}) matches the array document exactly, Db.users. find({tags:[" Java ","bike"]}) matches db.users.find({tags:[" Java ","bike"]}) matches db.users.find({tags:[" Java ","bike"]}) Db.users. Find ({tags:" Java "}) fuzzy matching, as long as tags with Java to show. Db.usersCopy the code
8. Fuzzy query
Select * from users where name like '%a%' db.users.find({name:/.*a.*/}) Db.users. find({name:/.*a$/}) db.users.find({name:/.*a$/}) db.users.find({name:/.*a$/})Copy the code
9. Document nested query
(example) {"_id" : ObjectId(" 5b58b9544983f690C7AB9687 "), "name" : "baby3", "age" : "baby3", "age" : 18, "address" : { "country" : "china", "city" : "hangzhou", "district" : "xihu", "dd" : "zhongguancunroad 10" } } { "_id" : ObjectId("5b58b9784983f690c7ab9688"), "name" : "xiaowang", "age" : 19, "address" : { "country" : "china", "city" : "shanghai", "district" : "pudong", "dd" : "Sjtu Park 10"}} The query should contain the outer field and the inner field, can not be in order to query. You can also query strictly in order. Db.users. find({"address.country":' China '}) country db.users.find({"address.country":' China '}) country Db.users. find({"address.city":'hangzhou'}) db.users.find({age:18,"address.city":'hangzhou'}) db.users.find({age:18,"address.city":'hangzhou'}) Db.users. find({age:{$lt:18},"address.city":' Hangzhou '}) can be restricted by conditions such as the 0 element that is less than 18 years old. Db.orders. find({'item.0. Count ':{$lt:2}}) multiple conditions and query db.orders.find({"item.count":{$gt:0,$lte:100}}) projection (map) returns specific fields Db.users. find({age:18},{name:1,age:1}) where age is 18. Db.users. find({age:{$gt:29}},{name:1,age:1}); db.users.find({age:{$gt:29},{name:1,age:1}); Db.users. find({age:{$gt:29}},{name:0}); db.users.find({age:{$gt:29}},{name:0}); Do not return the name field, everything else is returnedCopy the code
9. Projection (returns only specific fields)/ de-redo/aggregate
Projection (mapping) returns a specific field, _id if not specified. Flag as 1 for fields you want to return, such as name:1. Identify 0 for unwanted fields such as age:0. Db.users. find({age:18},{name:1,age:1}) where age is 18. Db.users. find({age:{$gt:29}},{name:1,age:1}); db.users.find({age:{$gt:29},{name:1,age:1}); Db.users. find({age:{$gt:29}},{name:0}); db.users.find({age:{$gt:29}},{name:0}); Db.users. Distinct ("name") db.Orders. Distinct ("items. Count ") db.Orders. Db.orders. distinct("item.count ",{age:18}) db.orders.distinct("item.count ",{age:18}) db.orders.distinct("item.count ",{age:18}) db.orders.distinct("item.count ",{age:18}) Db.users. Distinct ("city") DB.users. Distinct ("address.city") is equivalent to the items.count field Db. runCommand({distinct:"users",key:"name"}) For performance, use indexes as much as possible. Nodes can be queried preferentially. There are three types of statistical analysis: aggregation functions (early features), aggregation pipelines, and MapReduce (for big data analysis). Simply use the group method. 3.4 Expired, it is recommended to use a new aggregation. Db.collections. aggregate()+$group or db.collections.mapreduce Group db.users. Group ({key:{age:1}, cond:{age:{$gt:16}}, reduce:function(curr,result){ result.total +=1; Db.orders. Grop ({key:{name:1}, cond:{}, initial:{total:0}) reduce:function(curr.result){ result.total += curr.price; Db.orders. Group ({key:{name:1}, cond:{}, initial:{total:0}) reduce:function(curr,result){ result.total +=1; }, initial:{total:0}} db.orders. Group ({key:{name:1}, cond:{}, reduce:function(curr,result){ result.total =curr.price }, initial:{total:0} } )Copy the code
10 Null value query
Db.a.type () {"_id" : ObjectId(" 5fd9b25c1d2a682a33b3AB90 "), "y" : null} {"_id" : ObjectId("5fd9b25c1d2a682a33b3ab91"), "y" : 1 } { "_id" : ObjectId("5fd9b25c1d2a682a33b3ab92"), "y" : Db.a.type ({'y':null}) {"_id" : ObjectId(" 5fd9b25c1d2a682a33b3AB90 "), "y" : ObjectId(" 5fd9b25c1d2a682a33b3AB90 "), "y" : Db.a.type ({'z':null}) {"_id" : ObjectId(" 5FD9b25c1d2a682a33b3AB90 "), "y" : ObjectId(" 5FD9b25c1d2a682a33b3AB90 ") null } { "_id" : ObjectId("5fd9b25c1d2a682a33b3ab91"), "y" : 1 } { "_id" : ObjectId("5fd9b25c1d2a682a33b3ab92"), "y" : 2} Check whether z is null and whether a key exists. You can avoid the above problems. db.a.find({'z':{$in:[null],$exists:true}})Copy the code
11. The DB. The COLLECTION. The FIND added
Greater than or less than using find to show only 20 rows, Db.users. find({age:{$gt:18}}) db.users.find({age:{$gt:18,$lt:28}}) db.users.find({age:{$gt:18,$lt:28}}) Do it based on scope. The left and right can be included with GTE and LTECopy the code
FIND the operator
The operator | role |
---|---|
Query operator | |
Compare query operators | |
$eq | Matches a value equal to the specified value. |
$gt | Matches values greater than the specified value. |
$gte | Matches values greater than or equal to the specified value |
$in | Matches any value specified in the array. |
$lt | Matches values that are less than the specified value. |
$lte | Matches values that are less than or equal to the specified value. |
$ne | Matches all values that are not equal to the specified value. |
$nin | Does not match any values specified in the array. |
Logical query operator | |
$and | Querying the clause AND using a logical join returns all documents that match the conditions of both clauses. |
$not | Reverse the effect of the query expression and return documents that do not match the query expression. |
$nor | A logical join query for the NOR clause returns all documents that do not match the two clauses. |
$or | Using a logical join query clause OR returns all documents that match the conditions of any of the clauses. |
Element query operator | |
$exists | Matches documents with the specified field. |
$type | If the field is of the specified type, select document. |
Evaluate the query operator | |
$expr | Allows the use of aggregate expressions in the query language. |
$jsonSchema | Validate the document against the given JSON schema. |
$mod | Performs a modular operation on the value of the field and selects the document with the specified result. |
$regex | Selects documents whose values match the specified regular expression. |
$text | Perform text search |
$where | Matches documents that satisfy JavaScript expressions. |
Geospatial query operator | |
$geoIntersects | Select the geometry that intersects the GeoJSON geometry. The 2DSPHERE index is supported |
$geoWithin | Select the geometry within the boundary GeoJSON geometry. The 2DSphere and 2D indexes are supported. |
$near | Returns the geospatial object near the point. Geospatial indexes are required. |
$nearSphere | Returns a geospatial object near a point on the sphere. Geospatial indexes are required. |
Array query operator | |
$all | Matches an array containing all the elements specified in the query |
$elemMatch | If the elements in the array field match all the specified $elemMatch conditions, the document is selected. |
$size | If the array field is the specified size, select the document. |
Bitwise query operator | |
$bitsAllClear | Matches numeric or binary values where a set of bit positions all have the value 0. |
$bitsAllSet | Matches numeric or binary values where a set of bit positions all have the value 1. |
$bitsAnyClear | Matches numeric or binary values where any bit from a set of bit positions has a value of 0. |
$bitsAnySet | Matches numeric or binary values where any bit from a set of bit positions has a value of 1. |
Projection query operator | |
$ | The first element in the projection array that matches the query condition. |
$elemMatch | The first element in the projection array that matches the specified $elemMatch condition. |
$meta | Project the document score assigned during the $TEXT operation. |
$slice | Limits the number of elements projected from an array. Supports skipping and limiting slices. |