Updating nested document in MongoDB

To update nested documents in MongoDB, use the $set operator with dot notation to specify the exact path to the field you want to modify. This allows you to update deeply nested fields without affecting other parts of the document.

Syntax

db.collection.update(
    { "matchField": "value" },
    { $set: { "path.to.nested.field": "newValue" } }
);

Sample Data

Let us create a collection with a nested document ?

db.demo315.insertOne({
    _id: 101,
    details: [
        {
            Name: "Chris",
            subjects: [
                { id: 1001, SubjectName: "MySQL" }
            ]
        }
    ]
});
{ "acknowledged": true, "insertedId": 101 }

Display the document to verify the structure ?

db.demo315.find().pretty();
{
    "_id": 101,
    "details": [
        {
            "Name": "Chris",
            "subjects": [
                {
                    "id": 1001,
                    "SubjectName": "MySQL"
                }
            ]
        }
    ]
}

Example: Update Nested Array Element

Add a new subject at index 1 in the subjects array ?

db.demo315.update(
    { _id: 101 },
    { $set: { "details.0.subjects.1.id": 1004 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo315.find().pretty();
{
    "_id": 101,
    "details": [
        {
            "Name": "Chris",
            "subjects": [
                {
                    "id": 1001,
                    "SubjectName": "MySQL"
                },
                {
                    "id": 1004
                }
            ]
        }
    ]
}

Key Points

  • Use dot notation to specify the path: details.0.subjects.1.id
  • Array indices are zero-based (0 = first element, 1 = second element)
  • The $set operator creates the field if it doesn't exist

Conclusion

MongoDB's $set operator with dot notation provides precise control over nested document updates. Use array indices and field names to target specific nested elements efficiently.

Updated on: 2026-03-15T02:28:38+05:30

376 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements