在MongoDB中更新文档时有条件追加(多次插入)?
对于多个写入操作,请在MongoDB中使用bulkWrite()。让我们创建一个包含文档的集合-
> db.demo428.insertOne({ "Name" : "Chris", "Age" : 21 }); { "acknowledged" : true, "insertedId" : ObjectId("5e75f428bbc41e36cc3cae83") } > db.demo428.insertOne({ "Name" : "Chris", "Age" : 23 }); { "acknowledged" : true, "insertedId" : ObjectId("5e75f429bbc41e36cc3cae84") } > db.demo428.insertOne({ "Name" : "David", "Age" : 22 }); { "acknowledged" : true, "insertedId" : ObjectId("5e75f42abbc41e36cc3cae85") } > db.demo428.insertOne({ "Name" : "David", "Age" : 21 }); { "acknowledged" : true, "insertedId" : ObjectId("5e75f42abbc41e36cc3cae86") }
在find()方法的帮助下显示集合中的所有文档
> db.demo428.find();
这将产生以下输出-
{ "_id" : ObjectId("5e75f428bbc41e36cc3cae83"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e75f429bbc41e36cc3cae84"), "Name" : "Chris", "Age" : 23 } { "_id" : ObjectId("5e75f42abbc41e36cc3cae85"), "Name" : "David", "Age" : 22 } { "_id" : ObjectId("5e75f42abbc41e36cc3cae86"), "Name" : "David", "Age" : 21 }
以下是在MongoDB中更新文档时对条件upsert(insert)的查询-
> db.demo428.bulkWrite( ... [ ... { "updateOne": { ... "filter": { "Name": "David", "Age": 22 }, ... "update": { "$set": { "Info": {Name:"John"} } } ... }}, ... { "insertOne": { ... "document": { "Name": "Carol", "Age": 22, "Info": {Name:"John"}} ... }} ... ], ... { "ordered": false } ... ) { "acknowledged" : true, "deletedCount" : 0, "insertedCount" : 1, "matchedCount" : 1, "upsertedCount" : 0, "insertedIds" : { "1" : ObjectId("5e75f448bbc41e36cc3cae87") }, "upsertedIds" : { } }
在find()方法的帮助下显示集合中的所有文档-
> db.demo428.find();
这将产生以下输出-
{ "_id" : ObjectId("5e75f428bbc41e36cc3cae83"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e75f429bbc41e36cc3cae84"), "Name" : "Chris", "Age" : 23 } { "_id" : ObjectId("5e75f42abbc41e36cc3cae85"), "Name" : "David", "Age" : 22, "Info" : { "Name" : "John" } } { "_id" : ObjectId("5e75f42abbc41e36cc3cae86"), "Name" : "David", "Age" : 21 } { "_id" : ObjectId("5e75f448bbc41e36cc3cae87"), "Name" : "Carol", "Age" : 22, "Info" : { "Name" : "John" } }