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 query to update all documents matching specific IDs
To update all documents matching specific IDs in MongoDB, use updateMany() with the $in operator to specify multiple ID values in the filter criteria.
Syntax
db.collection.updateMany(
{ _id: { $in: [id1, id2, id3] } },
{ $set: { field: "newValue" } }
);
Sample Data
db.demo476.insertMany([
{ _id: 1, "Name": "Chris" },
{ _id: 2, "Name": "David" },
{ _id: 3, "Name": "Bob" },
{ _id: 4, "Name": "Carol" }
]);
{
"acknowledged": true,
"insertedIds": {
"0": 1,
"1": 2,
"2": 3,
"3": 4
}
}
Display all documents from the collection ?
db.demo476.find();
{ "_id": 1, "Name": "Chris" }
{ "_id": 2, "Name": "David" }
{ "_id": 3, "Name": "Bob" }
{ "_id": 4, "Name": "Carol" }
Example: Update Documents with IDs 1 and 3
Update the Name field to "Robert" for documents with _id values 1 and 3 ?
db.demo476.updateMany(
{ _id: { $in: [1, 3] } },
{ $set: { Name: "Robert" } }
);
{ "acknowledged": true, "matchedCount": 2, "modifiedCount": 2 }
Verify Result
db.demo476.find();
{ "_id": 1, "Name": "Robert" }
{ "_id": 2, "Name": "David" }
{ "_id": 3, "Name": "Robert" }
{ "_id": 4, "Name": "Carol" }
Key Points
- The
$inoperator matches documents where the _id field equals any value in the specified array. -
updateMany()updates all matching documents, whileupdateOne()updates only the first match. - The operation returns
matchedCountandmodifiedCountfor verification.
Conclusion
Use updateMany() with $in operator to efficiently update multiple documents by their specific IDs. This approach allows you to target exact documents without complex query conditions.
Advertisements
