Conditional upsert (multiple insert) when updating document in MongoDB?

To perform conditional upserts and multiple inserts when updating documents in MongoDB, use the bulkWrite() method. This allows you to combine update operations and insert operations in a single transaction-like operation.

Syntax

db.collection.bulkWrite([
    { "updateOne": {
        "filter": { field: value },
        "update": { $set: { newField: newValue } }
    }},
    { "insertOne": {
        "document": { field1: value1, field2: value2 }
    }}
], { "ordered": false });

Sample Data

db.demo428.insertMany([
    { "Name": "Chris", "Age": 21 },
    { "Name": "Chris", "Age": 23 },
    { "Name": "David", "Age": 22 },
    { "Name": "David", "Age": 21 }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": ObjectId("5e75f428bbc41e36cc3cae83"),
        "1": ObjectId("5e75f429bbc41e36cc3cae84"),
        "2": ObjectId("5e75f42abbc41e36cc3cae85"),
        "3": ObjectId("5e75f42abbc41e36cc3cae86")
    }
}

Example: Conditional Update and Insert

Update David's document where Age is 22 and insert a new Carol document ?

db.demo428.bulkWrite([
    { "updateOne": {
        "filter": { "Name": "David", "Age": 22 },
        "update": { "$set": { "Info": { Name: "John" } } }
    }},
    { "insertOne": {
        "document": { "Name": "Carol", "Age": 22, "Info": { Name: "John" } }
    }}
], { "ordered": false });
{
    "acknowledged": true,
    "deletedCount": 0,
    "insertedCount": 1,
    "matchedCount": 1,
    "upsertedCount": 0,
    "insertedIds": {
        "1": ObjectId("5e75f448bbc41e36cc3cae87")
    },
    "upsertedIds": {}
}

Verify Result

db.demo428.find();
{ "_id": ObjectId("5e75f428bbc41e36cc3cae83"), "Name": "Chris", "Age": 21 }
{ "_id": ObjectId("5e75f429bbc41e36cc3cae84"), "Name": "Chris", "Age": 23 }
{ "_id": ObjectId("5e75f42abbc41e36cc3cae85"), "Name": "David", "Age": 22, "Info": { "Name": "John" } }
{ "_id": ObjectId("5e75f42abbc41e36cc3cae86"), "Name": "David", "Age": 21 }
{ "_id": ObjectId("5e75f448bbc41e36cc3cae87"), "Name": "Carol", "Age": 22, "Info": { "Name": "John" } }

Key Points

  • ordered: false allows operations to continue even if one fails
  • Use updateOne, insertOne, replaceOne, or deleteOne within bulkWrite
  • The operation returns detailed statistics about matched, inserted, and modified documents

Conclusion

The bulkWrite() method efficiently combines multiple update and insert operations in MongoDB. Use ordered: false for better performance when operation order doesn't matter.

Updated on: 2026-03-15T02:57:09+05:30

537 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements