Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
modifiedCountshows actual documents changed (recommended approach) -
nModifiedin WriteResult provides the same information for legacy operations -
matchedCountshows 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.
Advertisements
