MongoDB query to update selected fields

To update selected fields in MongoDB, use the update() method with the $set operator. The $set operator modifies specific fields without affecting other document properties.

Syntax

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

Create Sample Data

Let us create a collection with sample documents ?

db.demo352.insertMany([
    { "Name": "Chris" },
    { "Name": "David" },
    { "Name": "Bob" },
    { "Name": "Mike" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e55510af8647eb59e5620ba"),
        ObjectId("5e55510ef8647eb59e5620bb"),
        ObjectId("5e555112f8647eb59e5620bc"),
        ObjectId("5e555115f8647eb59e5620bd")
    ]
}

Display all documents from the collection ?

db.demo352.find();
{ "_id": ObjectId("5e55510af8647eb59e5620ba"), "Name": "Chris" }
{ "_id": ObjectId("5e55510ef8647eb59e5620bb"), "Name": "David" }
{ "_id": ObjectId("5e555112f8647eb59e5620bc"), "Name": "Bob" }
{ "_id": ObjectId("5e555115f8647eb59e5620bd"), "Name": "Mike" }

Example: Update Selected Field

Update David's name to Robert using $set ?

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

Verify Result

Display all documents to verify the update ?

db.demo352.find();
{ "_id": ObjectId("5e55510af8647eb59e5620ba"), "Name": "Chris" }
{ "_id": ObjectId("5e55510ef8647eb59e5620bb"), "Name": "Robert" }
{ "_id": ObjectId("5e555112f8647eb59e5620bc"), "Name": "Bob" }
{ "_id": ObjectId("5e555115f8647eb59e5620bd"), "Name": "Mike" }

Conclusion

The $set operator allows you to update specific fields in MongoDB documents while preserving other existing fields. Use it with update() to modify only the fields you need to change.

Updated on: 2026-03-15T02:35:25+05:30

529 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements