在mongodb中,更新多个文档的写操作不是原子的。如果有3条记录A,B,C需要更新。
MongoDB是否:
查找 A,更新 A,查找 B,更新 B,查找 C,更新 C
或者
找到A,B,C并保存到内存,forEach,更新A,B,C?
在mongodb中,更新多个文档的写操作不是原子的。如果有3条记录A,B,C需要更新。
MongoDB是否:
查找 A,更新 A,查找 B,更新 B,查找 C,更新 C
或者
找到A,B,C并保存到内存,forEach,更新A,B,C?
请看这个例子
db.mycollection.find()
{ "_id" : 1, "name" : "A", "designation" : "developer", "company" : "XYZ" }
{ "_id" : 2, "name" : "B", "designation" : "developer", "company" : "XYZ", "expe
rience" : 2 }
{ "_id" : 3, "name" : "C", "designation" : "developer", "company" : "XYZ", "expe
rience" : 3 }
{ "_id" : 4, "name" : "D", "designation" : "developer", "company" : "XYZ", "expe
rience" : 5 }
{ "_id" : 5, "name" : "E", "designation" : "Manager", "company" : "XYZ", "experi
ence" : 10 }
{ "_id" : 6, "name" : "F", "designation" : "Manager", "company" : "XYZ", "experi
ence" : 10 }
{ "_id" : 7, "name" : "G", "designation" : "Manager", "company" : "ABC", "experi
ence" : 10 }
{ "_id" : 8, "name" : "H", "designation" : "Developer", "company" : "ABC", "expe
rience" : 5 }
{ "_id" : 9, "name" : "I", "designation" : "Developer", "company" : "XYZ", "expe
rience" : 5 }
我将根据以下标准对 mycollection 进行批量更新
XYZ 公司将其成员是具有 5 年经验的开发人员提升为高级开发人员
我在 Mongo shell 中的命令是
var bulk = db.mycollection.initializeUnorderedBulkOp();
bulk.find({ $and:[{company:"XYZ"}, {experience:5}] }).update({$set:{designation:"
senior developer", comments:"Congrats you have been promoted to senior developer
"}});
bulk.execute();
Mongo Shell 执行查询后我们将得到以下结果
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 2,
"nModified" : 2,
"nRemoved" : 0,
"upserted" : [ ]
})
符合我们公司条件的两个文件:“XYZ”和经验:5,这些文件已更新(_id:4,_id:9)
db.mycollection.find()
{ "_id" : 1, "name" : "A", "designation" : "developer", "company" : "XYZ" }
{ "_id" : 2, "name" : "B", "designation" : "developer", "company" : "XYZ", "expe
rience" : 2 }
{ "_id" : 3, "name" : "C", "designation" : "developer", "company" : "XYZ", "expe
rience" : 3 }
{ "_id" : 4, "name" : "D", "designation" : "senior developer", "company" : "XYZ"
, "experience" : 5, "comments" : "Congrats you have been promoted to senior deve
loper" }
{ "_id" : 5, "name" : "E", "designation" : "Manager", "company" : "XYZ", "experi
ence" : 10 }
{ "_id" : 6, "name" : "F", "designation" : "Manager", "company" : "XYZ", "experi
ence" : 10 }
{ "_id" : 7, "name" : "G", "designation" : "Manager", "company" : "ABC", "experi
ence" : 10 }
{ "_id" : 8, "name" : "H", "designation" : "Developer", "company" : "ABC", "expe
rience" : 5 }
{ "_id" : 9, "name" : "I", "designation" : "senior developer", "company" : "XYZ"
, "experience" : 5, "comments" : "Congrats you have been promoted to senior deve
loper" }
其他相关的有趣参考:
MongoDB 中的 findAndModify 和 update 有什么区别?
https://docs.mongodb.com/manual/reference/method/Bulk.find.update/
https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/
https://docs.mongodb.com/v3.2/reference/method/db.collection.findOneAndUpdate/
希望能帮助到你!!