MongoDB query to update the nested document?

To update a nested document in MongoDB, use the update() method with dot notation to specify the path to the nested field. This allows you to modify deeply embedded values without affecting the parent document structure.

Syntax

db.collection.update(
    { "filterField": "value" },
    { $set: { "parentField.nestedField.targetField": "newValue" } }
);

Sample Data

Let us create a collection with a nested document structure ?

db.demo607.insertOne({
    id: 1,
    "Info1": {
        "Name": "Chris",
        "Age": 21,
        "Info2": {
            "SubjectName": "MongoDB",
            "Marks": 89
        }
    }
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e9742a5f57d0dc0b182d62a")
}

Example: Update Nested Field

Display the current document ?

db.demo607.find();
{
    "_id": ObjectId("5e9742a5f57d0dc0b182d62a"),
    "id": 1,
    "Info1": {
        "Name": "Chris",
        "Age": 21,
        "Info2": {
            "SubjectName": "MongoDB",
            "Marks": 89
        }
    }
}

Update the nested Marks field from 89 to 90 ?

db.demo607.update(
    { id: 1 },
    { $set: { "Info1.Info2.Marks": 90 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Display the updated document ?

db.demo607.find().pretty();
{
    "_id": ObjectId("5e9742a5f57d0dc0b182d62a"),
    "id": 1,
    "Info1": {
        "Name": "Chris",
        "Age": 21,
        "Info2": {
            "SubjectName": "MongoDB",
            "Marks": 90
        }
    }
}

Key Points

  • Use dot notation to traverse nested document levels: "parentField.childField.targetField"
  • The $set operator updates only the specified field without modifying the entire document structure
  • Multiple nested levels can be accessed by chaining field names with dots

Conclusion

MongoDB's dot notation with the $set operator provides a clean way to update nested document fields. This approach preserves the document structure while precisely targeting the field that needs modification.

Updated on: 2026-03-15T03:49:19+05:30

508 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements