How to update a MongoDB document without overwriting the existing one?

To update only a field value in MongoDB, use update() along with $set. This won't overwrite the existing document but only modifies the specified fields.

Syntax

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

Sample Data

Let us first create a collection with documents ?

db.demo401.insertOne({
    "_id": 1001,
    "Name": "Chris",
    "SubjectName": "MongoDB",
    "Score": 45
});
{ "acknowledged": true, "insertedId": 1001 }

Example

Display all documents from the collection ?

db.demo401.find();
{ "_id": 1001, "Name": "Chris", "SubjectName": "MongoDB", "Score": 45 }

Update the Score field without overwriting other fields ?

db.demo401.update(
    { "_id": 1001 },
    { $set: { "Score": 89 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Display the updated document ?

db.demo401.find();
{ "_id": 1001, "Name": "Chris", "SubjectName": "MongoDB", "Score": 89 }

Key Points

  • The $set operator updates only the specified fields, leaving other fields unchanged.
  • Without $set, the update operation would replace the entire document.
  • Use updateOne() or updateMany() for modern MongoDB applications.

Conclusion

The $set operator with update() allows selective field updates without overwriting the entire document. This preserves existing data while modifying only the target fields.

Updated on: 2026-03-15T02:51:13+05:30

937 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements