How to keep appending subdocuments in MongoDB?

To append subdocuments in MongoDB, use the $push operator with the update() method. This operator adds new subdocuments to an existing array field without removing existing elements.

Syntax

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

Sample Data

Let us create a collection with documents −

db.demo587.insertMany([
    { "id": 101, "details": [{ Name: "Chris", Age: 21, Marks: 57 }] },
    { "id": 102, "details": [{ Name: "Bob", Age: 22, Marks: 78 }] }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e92ba01fd2d90c177b5bcc9"),
        ObjectId("5e92ba0efd2d90c177b5bcca")
    ]
}

Display all documents from the collection −

db.demo587.find();
{ "_id": ObjectId("5e92ba01fd2d90c177b5bcc9"), "id": 101, "details": [{ "Name": "Chris", "Age": 21, "Marks": 57 }] }
{ "_id": ObjectId("5e92ba0efd2d90c177b5bcca"), "id": 102, "details": [{ "Name": "Bob", "Age": 22, "Marks": 78 }] }

Example: Appending Subdocuments

Append a new subdocument to the details array for id 101 −

db.demo587.update(
    { "id": 101 },
    { "$push": { "details": { Subject: "MongoDB" } } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Display the updated documents −

db.demo587.find();
{
    "_id": ObjectId("5e92ba01fd2d90c177b5bcc9"),
    "id": 101,
    "details": [
        { "Name": "Chris", "Age": 21, "Marks": 57 },
        { "Subject": "MongoDB" }
    ]
}
{
    "_id": ObjectId("5e92ba0efd2d90c177b5bcca"),
    "id": 102,
    "details": [
        { "Name": "Bob", "Age": 22, "Marks": 78 }
    ]
}

Key Points

  • The $push operator appends values to array fields without affecting existing elements.
  • Use update() with a query filter to target specific documents.
  • Each $push operation adds exactly one element to the array.

Conclusion

The $push operator effectively appends subdocuments to arrays in MongoDB. It preserves existing array elements while adding new ones, making it ideal for continuously expanding document arrays.

Updated on: 2026-03-15T03:45:42+05:30

203 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements