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 $in operator matches documents where the _id field equals any value in the specified array.
  • updateMany() updates all matching documents, while updateOne() updates only the first match.
  • The operation returns matchedCount and modifiedCount for 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.

Updated on: 2026-03-15T03:06:23+05:30

863 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements