让我们创建一个包含文档的集合-
>db.demo550.insertOne({"Name":"Chris","details":[{"Marks":49,Result:"fail"},{"Marks":58,Result:"fail"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e8e35bd9e5f92834d7f05e4") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo550.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8e35bd9e5f92834d7f05e4"), "Name" : "Chris", "details" : [ { "Marks" : 49, "Result" : "fail" }, { "Marks" : 58, "Result" : "fail" } ] }
以下是查询以更新MongoDB中数组中的元素并执行批量操作-
> var all= db.demo550.initializeOrderedBulkOp(), ... itr = 0; > db.demo550.find({ "Name": "Chris", "details.Result": "fail" }).forEach(function(doc) { ... doc.details.filter(function(d){ return d.Result = "fail" }).forEach(function(d) { ... all.find({ "_id": doc._id, "details.Result": "fail" }).updateOne({ ... "$set": { "details.$.Result": "PASS" } ... }); ... itr++; ... if ( itr % 10== 0 ) { ... all.execute(); ... all = db.demo550.initializeOrderedBulkOp(); ... } ... }); ... if ( itr % 10 != 0 ) ... all.execute(); ... });
在find()
方法的帮助下显示集合中的所有文档-
> db.demo550.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8e35bd9e5f92834d7f05e4"), "Name" : "Chris", "details" : [ { "Marks" : 49, "Result" : "PASS" }, { "Marks" : 58, "Result" : "PASS" } ] }