How can we update a record in MongoDB?

To update a record in MongoDB, use the update() method with a query filter and update operators like $set. You can update based on _id or any field that uniquely identifies the document.

Syntax

db.collection.update(
    { "field": "value" },
    { $set: { "field": "newValue" } }
);

Create Sample Data

Let us create a collection with sample documents ?

db.demo458.insertMany([
    { _id: 101, "Name": "David" },
    { _id: 102, "Name": "Chris" },
    { _id: 103, "Name": "Bob" }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": 101,
        "1": 102,
        "2": 103
    }
}

Display all documents from the collection ?

db.demo458.find();
{ "_id": 101, "Name": "David" }
{ "_id": 102, "Name": "Chris" }
{ "_id": 103, "Name": "Bob" }

Example: Update Record by _id

Update the document with _id: 102 to change the name ?

db.demo458.update(
    { _id: 102 },
    { $set: { "Name": "David Miller" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Display all documents to verify the update ?

db.demo458.find();
{ "_id": 101, "Name": "David" }
{ "_id": 102, "Name": "David Miller" }
{ "_id": 103, "Name": "Bob" }

Key Points

  • Use $set operator to update specific fields without affecting other fields.
  • The _id field provides a unique identifier for targeted updates.
  • The WriteResult shows how many documents were matched and modified.

Conclusion

The update() method with $set operator allows precise field updates in MongoDB. Using _id ensures you update the exact document you intend to modify.

Updated on: 2026-03-15T03:02:59+05:30

436 Views

Advertisements