How to run MongoDB query to update only a specific field value?

To update only a specific field value in MongoDB, use the $set operator with the update() method. This allows you to modify particular fields without affecting other document data.

Syntax

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

Create Sample Data

Let us create a collection with sample documents ?

db.demo557.insertMany([
    { Name: "Chris" },
    { Name: "David" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e8f28e954b4472ed3e8e864"),
        ObjectId("5e8f28ee54b4472ed3e8e865")
    ]
}

Display all documents from the collection ?

db.demo557.find();
{ "_id": ObjectId("5e8f28e954b4472ed3e8e864"), "Name": "Chris" }
{ "_id": ObjectId("5e8f28ee54b4472ed3e8e865"), "Name": "David" }

Example: Update Specific Field

Update the Name field from "Chris" to "Robert" ?

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

Verify Result

Display all documents to verify the update ?

db.demo557.find();
{ "_id": ObjectId("5e8f28e954b4472ed3e8e864"), "Name": "Robert" }
{ "_id": ObjectId("5e8f28ee54b4472ed3e8e865"), "Name": "David" }

Key Points

  • The $set operator updates only the specified fields
  • Other fields in the document remain unchanged
  • Use updateOne() for single document updates or updateMany() for multiple documents

Conclusion

The $set operator with update() method provides precise field-level updates in MongoDB. This approach preserves existing document structure while modifying only the target fields.

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

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements