Updating Nested Embedded Documents in MongoDB?

To update nested embedded documents in MongoDB, use the positional operator ($) with update operations like $push, $set, or $addToSet. The positional operator identifies the array element that matches the query condition and allows you to modify nested documents within that element.

Syntax

db.collection.update(
    {"arrayField.nestedField": "matchValue"},
    {"$push": {"arrayField.$.nestedArray": newDocument}}
);

Sample Data

Let's create a collection with nested embedded documents ?

db.demo643.insertOne({
    details: [
        {
            "CountryName": "US",
            "StudentDetails": [
                {"Name": "Chris"},
                {"SubjectName": "MySQL"}
            ]
        },
        {
            "CountryName": "UK", 
            "StudentDetails": [
                {"Name": "Bob"},
                {"SubjectName": "Java"}
            ]
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e9c737f6c954c74be91e6e3")
}

Display all documents from the collection ?

db.demo643.find();
{
    "_id": ObjectId("5e9c737f6c954c74be91e6e3"),
    "details": [
        {
            "CountryName": "US",
            "StudentDetails": [
                {"Name": "Chris"},
                {"SubjectName": "MySQL"}
            ]
        },
        {
            "CountryName": "UK",
            "StudentDetails": [
                {"Name": "Bob"},
                {"SubjectName": "Java"}
            ]
        }
    ]
}

Example: Adding to Nested Array

Add a new marks document to the UK country's StudentDetails array ?

db.demo643.update(
    {"details.CountryName": "UK"},
    {"$push": {"details.$.StudentDetails": {"Marks": 78}}}
);
WriteResult({"nMatched": 1, "nUpserted": 0, "nModified": 1})

Verify Result

Display the updated document ?

db.demo643.find().pretty();
{
    "_id": ObjectId("5e9c737f6c954c74be91e6e3"),
    "details": [
        {
            "CountryName": "US",
            "StudentDetails": [
                {"Name": "Chris"},
                {"SubjectName": "MySQL"}
            ]
        },
        {
            "CountryName": "UK",
            "StudentDetails": [
                {"Name": "Bob"},
                {"SubjectName": "Java"},
                {"Marks": 78}
            ]
        }
    ]
}

Key Points

  • The $ operator matches the first array element that satisfies the query condition
  • Use $push to add new elements to nested arrays
  • Use $set to update existing values in nested documents

Conclusion

The positional operator ($) is essential for updating nested embedded documents in MongoDB. It identifies the matching array element and allows precise modifications to deeply nested structures using dot notation.

Updated on: 2026-03-15T03:15:06+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements