Perform multiple updates with bulk operations and update elements in an array in MongoDB


For this, use initializeOrderedBulkOp(). It initializes and returns a new Bulk() operations builder for a collection. The builder constructs an ordered list of write operations that MongoDB executes in bulk.

Let us create a collection with documents −

>db.demo550.insertOne({"Name":"Chris","details":[{"Marks":49,Result:"fail"},{"Marks":58,Result:"fail"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8e35bd9e5f92834d7f05e4")
}

Display all documents from a collection with the help of find() method −

> db.demo550.find();

This will produce the following output −

{ "_id" : ObjectId("5e8e35bd9e5f92834d7f05e4"), "Name" : "Chris", "details" : [ { "Marks" : 49, "Result" : "fail" }, { "Marks" : 58, "Result" : "fail" } ] }

Following is the query to update elements in an array in MongoDB and perform bulk operations −

> 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();
... });

Display all documents from a collection with the help of find() method −

> db.demo550.find();

This will produce the following output −

{ "_id" : ObjectId("5e8e35bd9e5f92834d7f05e4"), "Name" : "Chris", "details" : [ { "Marks" : 49, "Result" : "PASS" }, { "Marks" : 58, "Result" : "PASS" } ] }

Updated on: 14-May-2020

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements