MongoDB query to update only certain fields?

To update only certain fields in MongoDB, use the $set operator. This operator modifies specific fields without affecting other existing fields in the document.

Syntax

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

Sample Data

Let us create a collection with sample documents −

db.demo265.insertMany([
    {"id": 101, "Name": "Chris"},
    {"id": 102, "Name": "Bob"},
    {"id": 103, "Name": "David"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e480d781627c0c63e7dbaa4"),
        ObjectId("5e480d7d1627c0c63e7dbaa5"),
        ObjectId("5e480d841627c0c63e7dbaa6")
    ]
}

Display all documents from the collection −

db.demo265.find();
{ "_id": ObjectId("5e480d781627c0c63e7dbaa4"), "id": 101, "Name": "Chris" }
{ "_id": ObjectId("5e480d7d1627c0c63e7dbaa5"), "id": 102, "Name": "Bob" }
{ "_id": ObjectId("5e480d841627c0c63e7dbaa6"), "id": 103, "Name": "David" }

Example: Update Specific Field

Update only the id field for David's document −

db.demo265.update(
    {"Name": "David"},
    {$set: {"id": 10004}}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo265.find();
{ "_id": ObjectId("5e480d781627c0c63e7dbaa4"), "id": 101, "Name": "Chris" }
{ "_id": ObjectId("5e480d7d1627c0c63e7dbaa5"), "id": 102, "Name": "Bob" }
{ "_id": ObjectId("5e480d841627c0c63e7dbaa6"), "id": 10004, "Name": "David" }

Key Points

  • $set updates only the specified fields, leaving other fields unchanged.
  • If the field doesn't exist, $set will create it.
  • Use updateOne() for single document updates or updateMany() for multiple documents.

Conclusion

The $set operator provides precise field-level updates without modifying the entire document. This approach ensures data integrity by preserving unchanged fields while updating only the necessary ones.

Updated on: 2026-03-15T02:10:07+05:30

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements