Multiple atomic updates using MongoDB?

Multiple atomic updates in MongoDB allow you to update multiple documents that match a query condition in a single operation. Use the updateMany() method or the legacy update() method with the multi parameter set to true.

Syntax

// Modern approach
db.collection.updateMany(
    { filter },
    { $set: { field: "newValue" } }
);

// Legacy approach
db.collection.update(
    { filter },
    { $set: { field: "newValue" } },
    { multi: true }
);

Sample Data

db.demo699.insertMany([
    { Name: "Chris Brown" },
    { Name: "David Miller" },
    { Name: "Chris Brown" },
    { Name: "John Doe" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ea6e370551299a9f98c93a7"),
        ObjectId("5ea6e37a551299a9f98c93a8"),
        ObjectId("5ea6e381551299a9f98c93a9"),
        ObjectId("5ea6e38a551299a9f98c93aa")
    ]
}

Example: Multiple Atomic Updates

Update all documents with Name "Chris Brown" to "Adam Smith" ?

db.demo699.update(
    { Name: "Chris Brown" },
    { $set: { Name: "Adam Smith" } },
    { multi: true }
);
WriteResult({ "nMatched": 2, "nUpserted": 0, "nModified": 2 })

Verify Result

db.demo699.find();
{ "_id": ObjectId("5ea6e370551299a9f98c93a7"), "Name": "Adam Smith" }
{ "_id": ObjectId("5ea6e37a551299a9f98c93a8"), "Name": "David Miller" }
{ "_id": ObjectId("5ea6e381551299a9f98c93a9"), "Name": "Adam Smith" }
{ "_id": ObjectId("5ea6e38a551299a9f98c93aa"), "Name": "John Doe" }

Modern Approach

Use updateMany() for better readability ?

db.demo699.updateMany(
    { Name: "Adam Smith" },
    { $set: { Name: "Chris Brown" } }
);
{
    "acknowledged": true,
    "matchedCount": 2,
    "modifiedCount": 2
}

Key Points

  • Set multi: true in legacy update() to update multiple documents
  • updateMany() is the preferred modern approach
  • All matching documents are updated atomically in a single operation

Conclusion

Multiple atomic updates ensure all matching documents are modified together. Use updateMany() for modern MongoDB versions or update() with multi: true for legacy compatibility.

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

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements