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
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: 3indicating 3 documents were found and modified. - Use
updateMany()as the modern alternative toupdate()withmulti: 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.
Advertisements
