How to push new items to an array inside of an object in MongoDB?

To push new items to an array inside of an object in MongoDB, use the $push operator combined with the $elemMatch operator to match the specific object, then use the $ positional operator to target the array field.

Syntax

db.collection.update(
    {
        "_id": documentId,
        "arrayField": { "$elemMatch": { "matchField": "matchValue" } }
    },
    {
        "$push": { "arrayField.$.targetArray": "newValue" }
    }
);

Sample Data

Let us create a collection with documents ?

db.pushNewItemsDemo.insertOne({
    "_id": 1,
    "StudentScore": 56,
    "StudentOtherDetails": [
        {
            "StudentName": "John",
            "StudentFriendName": ["Bob", "Carol"]
        },
        {
            "StudentName": "David",
            "StudentFriendName": ["Mike", "Sam"]
        }
    ]
});
{ "acknowledged": true, "insertedId": 1 }

Display the document to verify the data ?

db.pushNewItemsDemo.find();
{
    "_id": 1,
    "StudentScore": 56,
    "StudentOtherDetails": [
        { "StudentName": "John", "StudentFriendName": ["Bob", "Carol"] },
        { "StudentName": "David", "StudentFriendName": ["Mike", "Sam"] }
    ]
}

Example: Push Item to Nested Array

Push "James" to David's StudentFriendName array ?

db.pushNewItemsDemo.update(
    {
        "_id": 1,
        "StudentOtherDetails": { "$elemMatch": { "StudentName": "David" } }
    },
    {
        "$push": { "StudentOtherDetails.$.StudentFriendName": "James" }
    }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.pushNewItemsDemo.find();
{
    "_id": 1,
    "StudentScore": 56,
    "StudentOtherDetails": [
        { "StudentName": "John", "StudentFriendName": ["Bob", "Carol"] },
        { "StudentName": "David", "StudentFriendName": ["Mike", "Sam", "James"] }
    ]
}

How It Works

  • $elemMatch finds the object in the array that matches the condition (StudentName: "David")
  • $ positional operator identifies the matched array element's position
  • $push adds the new value to the specified nested array field

Conclusion

Use $elemMatch to match objects within arrays, then combine $push with the $ positional operator to add new items to nested arrays. This approach ensures you update the correct object's array field.

Updated on: 2026-03-15T01:24:20+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements