在 MongoDB 中更新文档时进行条件 upsert(多次插入)?
对于多个写操作,在 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(插入)的查询 -
> 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" } }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP