In MongoDB how do you use $set to update a nested value/embedded document?

In MongoDB, use the $set operator with dot notation to update values inside nested documents (embedded documents). This allows you to modify specific fields within nested objects without replacing the entire document.

Syntax

db.collectionName.update(
    { "matchCondition": "value" },
    { $set: { "outerField.innerField": "newValue" } }
);

Sample Data

Let us create a collection with a nested document ?

db.updateNestedValueDemo.insertOne({
    "CustomerName": "Chris",
    "CustomerDetails": {
        "CustomerAge": 25,
        "CustomerCompanyName": "Google",
        "CustomerCityName": "US"
    }
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5c8fccc4d3c9d04998abf015")
}

Display the document to see the current structure ?

db.updateNestedValueDemo.find().pretty();
{
    "_id": ObjectId("5c8fccc4d3c9d04998abf015"),
    "CustomerName": "Chris",
    "CustomerDetails": {
        "CustomerAge": 25,
        "CustomerCompanyName": "Google",
        "CustomerCityName": "US"
    }
}

Example: Update Nested Field

Update the nested field "CustomerCompanyName" from "Google" to "Dell" ?

db.updateNestedValueDemo.update(
    {},
    { $set: { "CustomerDetails.CustomerCompanyName": "Dell" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.updateNestedValueDemo.find().pretty();
{
    "_id": ObjectId("5c8fccc4d3c9d04998abf015"),
    "CustomerName": "Chris",
    "CustomerDetails": {
        "CustomerAge": 25,
        "CustomerCompanyName": "Dell",
        "CustomerCityName": "US"
    }
}

Key Points

  • Use dot notation ("outerField.innerField") to target nested fields
  • $set modifies only the specified field, leaving other nested fields unchanged
  • Empty query condition {}

Conclusion

The $set operator with dot notation provides precise control over nested document updates. This approach preserves the document structure while modifying only the target field within embedded documents.

Updated on: 2026-03-15T00:15:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements