在mongodb中,更新多个文档的写操作不是原子的。如果有3个记录A,B,C需要更新。
mongodb:
找到A,更新A,找到B,更新B,找到C,更新C
或
找到A,B,C并保存到内存,forEach,更新A,B,C?
答案 0 :(得分:0)
请参阅此示例
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" }
其他相关的有趣参考文献:
What's the difference between findAndModify and update in MongoDB?
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/
希望它能帮助!!