Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
