MongoDB concurrent update with sub collection?

To perform concurrent updates with sub collections in MongoDB, use the update() method combined with the $push operator and dot notation to reach nested fields within embedded documents and arrays.

Syntax

db.collection.update(
    { "field": "value" },
    { $push: { "parentField.subField.arrayField": newValue } }
);

Create Sample Data

Let us create a collection with documents ?

db.demo547.insertOne({
    Name: "Chris",
    Test: {
        "FirstTest": {
            Scores: [56, 29, 76]
        },
        "SecondTest": {
            Scores: [98, 91, 78]
        }
    }
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e8e2d579e5f92834d7f05dd")
}

Display Current Data

db.demo547.find();
{
    "_id": ObjectId("5e8e2d579e5f92834d7f05dd"),
    "Name": "Chris",
    "Test": {
        "FirstTest": {
            "Scores": [56, 29, 76]
        },
        "SecondTest": {
            "Scores": [98, 91, 78]
        }
    }
}

Concurrent Update with Sub Collection

Following is the query for concurrent update with subcollection ?

db.demo547.update(
    {"Name": "Chris"},
    { $push: { "Test.FirstTest.Scores": 99 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo547.find();
{
    "_id": ObjectId("5e8e2d579e5f92834d7f05dd"),
    "Name": "Chris",
    "Test": {
        "FirstTest": {
            "Scores": [56, 29, 76, 99]
        },
        "SecondTest": {
            "Scores": [98, 91, 78]
        }
    }
}

Conclusion

Use $push with dot notation to append values to arrays within nested sub collections. The dot notation "Test.FirstTest.Scores" traverses the nested document structure to reach the target array for concurrent updates.

Updated on: 2026-03-15T03:32:25+05:30

550 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements