Cannot push into an array from MongoDB?

To push into an array with MongoDB, use the $push operator. This operator adds a new element to the end of an existing array field in a document.

Syntax

db.collection.update(
    { <query> },
    { $push: { <arrayField>: <value> } }
);

Sample Data

Let us create a collection with documents ?

db.demo445.insertOne({
    "ListOfFriends": ["Robert", "Mike", "Sam", "Carol", "David", "Mike"]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e78f099bbc41e36cc3caec2")
}

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

db.demo445.find().pretty();
{
    "_id": ObjectId("5e78f099bbc41e36cc3caec2"),
    "ListOfFriends": [
        "Robert",
        "Mike",
        "Sam",
        "Carol",
        "David",
        "Mike"
    ]
}

Example: Push Element to Array

Following is the query to push into an array ?

db.demo445.update(
    { _id: ObjectId("5e78f099bbc41e36cc3caec2") },
    { $push: { ListOfFriends: "Chris Brown" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

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

db.demo445.find().pretty();
{
    "_id": ObjectId("5e78f099bbc41e36cc3caec2"),
    "ListOfFriends": [
        "Robert",
        "Mike",
        "Sam",
        "Carol",
        "David",
        "Mike",
        "Chris Brown"
    ]
}

Conclusion

The $push operator successfully adds new elements to arrays in MongoDB documents. It appends values to the end of the specified array field without affecting existing elements.

Updated on: 2026-03-15T03:00:23+05:30

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements