MongoDB - update partial number of documents?

To update multiple documents in MongoDB, use the multi: true option in the update() method. By default, MongoDB updates only the first matching document.

Syntax

db.collection.update(
    { "field": "matchValue" },
    { $set: { "field": "newValue" } },
    { multi: true }
);

Sample Data

db.demo312.insertMany([
    { "FirstName": "Robert" },
    { "FirstName": "Bob" },
    { "FirstName": "Robert" },
    { "FirstName": "David" },
    { "FirstName": "Robert" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e50ce16f8647eb59e56204a"),
        ObjectId("5e50ce19f8647eb59e56204b"),
        ObjectId("5e50ce1cf8647eb59e56204c"),
        ObjectId("5e50ce20f8647eb59e56204d"),
        ObjectId("5e50ce22f8647eb59e56204e")
    ]
}

Display Current Documents

db.demo312.find();
{ "_id": ObjectId("5e50ce16f8647eb59e56204a"), "FirstName": "Robert" }
{ "_id": ObjectId("5e50ce19f8647eb59e56204b"), "FirstName": "Bob" }
{ "_id": ObjectId("5e50ce1cf8647eb59e56204c"), "FirstName": "Robert" }
{ "_id": ObjectId("5e50ce20f8647eb59e56204d"), "FirstName": "David" }
{ "_id": ObjectId("5e50ce22f8647eb59e56204e"), "FirstName": "Robert" }

Example: Update Multiple Documents

Update all documents where FirstName is "Robert" to "Sam" ?

db.demo312.update(
    { "FirstName": "Robert" },
    { $set: { "FirstName": "Sam" } },
    { multi: true }
);
WriteResult({ "nMatched": 3, "nUpserted": 0, "nModified": 3 })

Verify Result

db.demo312.find();
{ "_id": ObjectId("5e50ce16f8647eb59e56204a"), "FirstName": "Sam" }
{ "_id": ObjectId("5e50ce19f8647eb59e56204b"), "FirstName": "Bob" }
{ "_id": ObjectId("5e50ce1cf8647eb59e56204c"), "FirstName": "Sam" }
{ "_id": ObjectId("5e50ce20f8647eb59e56204d"), "FirstName": "David" }
{ "_id": ObjectId("5e50ce22f8647eb59e56204e"), "FirstName": "Sam" }

Key Points

  • Without multi: true, only the first matching document is updated.
  • The WriteResult shows nMatched: 3 indicating 3 documents were found and modified.
  • Use updateMany() as the modern alternative to update() with multi: true.

Conclusion

Use multi: true with the update() method to modify multiple matching documents. The WriteResult confirms how many documents were matched and modified in the operation.

Updated on: 2026-03-15T02:22:38+05:30

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements