Update only specific fields in MongoDB?

To update only specific fields in MongoDB, use the $set operator. This operator modifies the value of a field without affecting other fields in the document.

Syntax

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

Sample Data

db.updateOnlySpecificFieldDemo.insertMany([
    { "EmployeeName": "John", "EmployeeCountryName": "UK" },
    { "EmployeeName": "Larry", "EmployeeCountryName": "US" },
    { "EmployeeName": "David", "EmployeeCountryName": "AUS" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c9ea849d628fa4220163b72"),
        ObjectId("5c9ea853d628fa4220163b73"),
        ObjectId("5c9ea85bd628fa4220163b74")
    ]
}

Display All Documents

db.updateOnlySpecificFieldDemo.find().pretty();
{
    "_id": ObjectId("5c9ea849d628fa4220163b72"),
    "EmployeeName": "John",
    "EmployeeCountryName": "UK"
}
{
    "_id": ObjectId("5c9ea853d628fa4220163b73"),
    "EmployeeName": "Larry",
    "EmployeeCountryName": "US"
}
{
    "_id": ObjectId("5c9ea85bd628fa4220163b74"),
    "EmployeeName": "David",
    "EmployeeCountryName": "AUS"
}

Example: Update Specific Field

Update only the "EmployeeName" field for the document with specific _id ?

db.updateOnlySpecificFieldDemo.update(
    { _id: ObjectId("5c9ea849d628fa4220163b72") },
    { $set: { "EmployeeName": "Robert" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.updateOnlySpecificFieldDemo.find().pretty();
{
    "_id": ObjectId("5c9ea849d628fa4220163b72"),
    "EmployeeName": "Robert",
    "EmployeeCountryName": "UK"
}
{
    "_id": ObjectId("5c9ea853d628fa4220163b73"),
    "EmployeeName": "Larry",
    "EmployeeCountryName": "US"
}
{
    "_id": ObjectId("5c9ea85bd628fa4220163b74"),
    "EmployeeName": "David",
    "EmployeeCountryName": "AUS"
}

Conclusion

The $set operator updates only the specified field while preserving all other existing fields. This makes it ideal for partial document updates without overwriting the entire document.

Updated on: 2026-03-15T00:39:10+05:30

871 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements