Update only a specific value in a MongoDB document

To update only a specific value in a MongoDB document, use the $set operator with update() or updateOne(). This operator modifies only the specified fields without affecting other document data.

Syntax

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

Create Sample Data

db.demo201.insertMany([
    { "ClientName": "Chris Brown", "ClientAge": 26 },
    { "ClientName": "David Miller", "ClientAge": 35 },
    { "ClientName": "Carol Taylor", "ClientAge": 28 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3c39ca03d395bdc21346e5"),
        ObjectId("5e3c39d403d395bdc21346e6"),
        ObjectId("5e3c39e603d395bdc21346e7")
    ]
}

Display all documents from the collection ?

db.demo201.find();
{ "_id": ObjectId("5e3c39ca03d395bdc21346e5"), "ClientName": "Chris Brown", "ClientAge": 26 }
{ "_id": ObjectId("5e3c39d403d395bdc21346e6"), "ClientName": "David Miller", "ClientAge": 35 }
{ "_id": ObjectId("5e3c39e603d395bdc21346e7"), "ClientName": "Carol Taylor", "ClientAge": 28 }

Example: Update Specific Field

Update the ClientName for the document with ClientAge 35 ?

db.demo201.updateOne(
    { "ClientAge": 35 },
    { $set: { "ClientName": "John Doe" } }
);
{
    "acknowledged": true,
    "matchedCount": 1,
    "modifiedCount": 1
}

Verify Result

db.demo201.find();
{ "_id": ObjectId("5e3c39ca03d395bdc21346e5"), "ClientName": "Chris Brown", "ClientAge": 26 }
{ "_id": ObjectId("5e3c39d403d395bdc21346e6"), "ClientName": "John Doe", "ClientAge": 35 }
{ "_id": ObjectId("5e3c39e603d395bdc21346e7"), "ClientName": "Carol Taylor", "ClientAge": 28 }

Key Points

  • $set updates only the specified fields, leaving other fields unchanged
  • updateOne() updates the first matching document
  • Use updateMany() to update all matching documents

Conclusion

The $set operator allows precise field updates without modifying the entire document. Use updateOne() for single document updates and updateMany() for multiple documents.

Updated on: 2026-03-15T01:43:06+05:30

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements