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
Update values in multiple documents with multi parameter in MongoDB?
To update values in multiple documents in MongoDB, use the multi: true parameter in the update operation. By default, MongoDB updates only the first matching document, but setting multi: true updates all documents that match the query criteria.
Syntax
db.collection.update(
{ query },
{ $set: { field: "newValue" } },
{ multi: true }
);
Sample Data
Let us create a collection with sample documents ?
db.demo390.insertMany([
{ "FirstName": "Chris" },
{ "FirstName": "David" },
{ "FirstName": "Bob" },
{ "FirstName": "Chris" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e5d1f3a22064be7ab44e7fa"),
ObjectId("5e5d1f3e22064be7ab44e7fb"),
ObjectId("5e5d1f4122064be7ab44e7fc"),
ObjectId("5e5d1f4422064be7ab44e7fd")
]
}
Display all documents from the collection ?
db.demo390.find();
{ "_id": ObjectId("5e5d1f3a22064be7ab44e7fa"), "FirstName": "Chris" }
{ "_id": ObjectId("5e5d1f3e22064be7ab44e7fb"), "FirstName": "David" }
{ "_id": ObjectId("5e5d1f4122064be7ab44e7fc"), "FirstName": "Bob" }
{ "_id": ObjectId("5e5d1f4422064be7ab44e7fd"), "FirstName": "Chris" }
Example: Update Multiple Documents
Update all documents where FirstName is "Chris" to "John" using multi: true ?
db.demo390.update(
{ FirstName: "Chris" },
{ $set: { "FirstName": "John" } },
{ multi: true }
);
WriteResult({ "nMatched": 2, "nUpserted": 0, "nModified": 2 })
Verify Result
Display the updated documents ?
db.demo390.find();
{ "_id": ObjectId("5e5d1f3a22064be7ab44e7fa"), "FirstName": "John" }
{ "_id": ObjectId("5e5d1f3e22064be7ab44e7fb"), "FirstName": "David" }
{ "_id": ObjectId("5e5d1f4122064be7ab44e7fc"), "FirstName": "Bob" }
{ "_id": ObjectId("5e5d1f4422064be7ab44e7fd"), "FirstName": "John" }
Key Points
- Without
multi: true, only the first matching document gets updated. - The
WriteResultshowsnMatched: 2andnModified: 2, confirming both "Chris" documents were updated. - Use
updateMany()as a modern alternative toupdate()withmulti: true.
Conclusion
The multi: true parameter ensures all matching documents are updated, not just the first one. This is essential for bulk updates across multiple documents in MongoDB collections.
Advertisements
