Implement MongoDB $push in embedded document array?

To implement MongoDB $push in an embedded document array, use the $push operator to add new documents to an existing array field within a document.

Syntax

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

Sample Data

Let us create a collection with documents ?

db.demo288.insertOne({
    "Name": "Chris",
    "details": [
        {"CountryName": "US", "Marks": 78},
        {"CountryName": "UK", "Marks": 68}
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e4c0393f49383b52759cbbe")
}

Display all documents from a collection with the help of find() method ?

db.demo288.find();
{
    "_id": ObjectId("5e4c0393f49383b52759cbbe"),
    "Name": "Chris",
    "details": [
        {"CountryName": "US", "Marks": 78},
        {"CountryName": "UK", "Marks": 68}
    ]
}

Example: Adding New Document to Array

Following is the query to implement $push in embedded document array ?

db.demo288.update(
    {Name: "Chris"},
    {$push: {"details": {"CountryName": "AUS", "Marks": 98}}},
    {upsert: true}
);
WriteResult({"nMatched": 1, "nUpserted": 0, "nModified": 1})

Verify Result

Display all documents from a collection with the help of find() method ?

db.demo288.find();
{
    "_id": ObjectId("5e4c0393f49383b52759cbbe"),
    "Name": "Chris",
    "details": [
        {"CountryName": "US", "Marks": 78},
        {"CountryName": "UK", "Marks": 68},
        {"CountryName": "AUS", "Marks": 98}
    ]
}

Conclusion

The $push operator successfully adds new embedded documents to existing arrays. The new document is appended to the end of the array, preserving the original order of existing elements.

Updated on: 2026-03-15T02:18:30+05:30

320 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements