Get number of updated documents in MongoDB?

To get the number of updated documents in MongoDB, you can use the WriteResult returned by update operations or the modern modifiedCount property in newer MongoDB versions.

Syntax

// Legacy update() method
db.collection.update(query, update, options);
WriteResult({ "nMatched": X, "nModified": Y })

// Modern updateMany() method  
db.collection.updateMany(query, update);
{ "modifiedCount": Y }

Sample Data

db.getNumberOfUpdatedDocumentsDemo.insertMany([
    {"StudentName": "David"},
    {"StudentName": "Chris"}, 
    {"StudentName": "Robert"},
    {"StudentName": "Ramit"},
    {"StudentName": "Adam"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ca28c1d6304881c5ce84bad"),
        ObjectId("5ca28c226304881c5ce84bae"),
        ObjectId("5ca28c276304881c5ce84baf"),
        ObjectId("5ca28c366304881c5ce84bb0"),
        ObjectId("5ca28c436304881c5ce84bb1")
    ]
}

Method 1: Using updateMany() (Recommended)

db.getNumberOfUpdatedDocumentsDemo.updateMany(
    {},
    { $set: {"StudentName": "Carol"} }
);
{
    "acknowledged": true,
    "matchedCount": 5,
    "modifiedCount": 5
}

Method 2: Using Legacy update() with WriteResult

db.getNumberOfUpdatedDocumentsDemo.update(
    {},
    { $set: {"StudentName": "Carol"} },
    { multi: true }
);
WriteResult({ "nMatched": 5, "nUpserted": 0, "nModified": 5 })

Verify Result

db.getNumberOfUpdatedDocumentsDemo.find();
{ "_id": ObjectId("5ca28c1d6304881c5ce84bad"), "StudentName": "Carol" }
{ "_id": ObjectId("5ca28c226304881c5ce84bae"), "StudentName": "Carol" }
{ "_id": ObjectId("5ca28c276304881c5ce84baf"), "StudentName": "Carol" }
{ "_id": ObjectId("5ca28c366304881c5ce84bb0"), "StudentName": "Carol" }
{ "_id": ObjectId("5ca28c436304881c5ce84bb1"), "StudentName": "Carol" }

Key Points

  • modifiedCount shows actual documents changed (recommended approach)
  • nModified in WriteResult provides the same information for legacy operations
  • matchedCount shows documents that matched the query criteria

Conclusion

Use updateMany() and check modifiedCount for the most reliable way to get the number of updated documents. Legacy update() with WriteResult also provides this information through nModified.

Updated on: 2026-03-15T00:45:29+05:30

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements