How do I push elements to an existing array in MongoDB?

To push elements to an existing array in MongoDB, use the $addToSet or $push operators with the update() method. The $addToSet adds elements only if they don't already exist, while $push always adds elements regardless of duplicates.

Syntax

// Using $addToSet (prevents duplicates)
db.collection.update(
    {query},
    { $addToSet: { "arrayField": "newElement" } }
);

// Using $push (allows duplicates)
db.collection.update(
    {query},
    { $push: { "arrayField": "newElement" } }
);

Sample Data

Let us create a collection with a document containing an array ?

db.pushElements.insertOne({
    "Comments": ["Good", "Awesome", "Nice"]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd682597924bb85b3f48953")
}

View the initial document ?

db.pushElements.find().pretty();
{
    "_id": ObjectId("5cd682597924bb85b3f48953"),
    "Comments": [
        "Good",
        "Awesome",
        "Nice"
    ]
}

Method 1: Using $addToSet (Prevents Duplicates)

Add "Cool" to the Comments array using $addToSet ?

db.pushElements.update(
    {_id: ObjectId("5cd682597924bb85b3f48953")},
    { $addToSet: {"Comments": "Cool"} }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Method 2: Using $push (Allows Duplicates)

Add "Excellent" using $push ?

db.pushElements.update(
    {_id: ObjectId("5cd682597924bb85b3f48953")},
    { $push: {"Comments": "Excellent"} }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Check the updated document ?

db.pushElements.find().pretty();
{
    "_id": ObjectId("5cd682597924bb85b3f48953"),
    "Comments": [
        "Good",
        "Awesome",
        "Nice",
        "Cool",
        "Excellent"
    ]
}

Key Differences

Operator Behavior Use Case
$addToSet Prevents duplicates Unique elements only
$push Allows duplicates All elements, including duplicates

Conclusion

Use $addToSet when you need unique array elements and $push when duplicates are acceptable. Both operators effectively add elements to existing arrays in MongoDB documents.

Updated on: 2026-03-15T01:14:48+05:30

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements