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

To perform multiple updates with bulk operations and update elements in an array in MongoDB, 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.

Syntax

var bulk = db.collection.initializeOrderedBulkOp();
bulk.find({query}).updateOne({$set: {field: value}});
bulk.execute();

Sample Data

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();
{ "_id" : ObjectId("5e8e35bd9e5f92834d7f05e4"), "Name" : "Chris", "details" : [ { "Marks" : 49, "Result" : "fail" }, { "Marks" : 58, "Result" : "fail" } ] }

Example: Bulk Update Array Elements

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

Verify Result

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

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

Key Points

  • The $ positional operator updates the first matching array element
  • Bulk operations execute in batches for better performance
  • The code processes updates in groups of 10 to optimize memory usage

Conclusion

MongoDB bulk operations with initializeOrderedBulkOp() provide efficient batch processing for multiple updates. Combined with the positional operator, you can update array elements in bulk while maintaining optimal performance.

Updated on: 2026-03-15T03:32:39+05:30

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements