$push vs $addToSet in MongoDB: Key Differences and Usage
$push adds a value to an array regardless of duplicates, while $addToSet adds a value only if it does not already exist in the array, preventing duplicates. Use $push for simple appends and $addToSet to maintain unique array elements.Quick Comparison
Here is a quick side-by-side comparison of $push and $addToSet in MongoDB.
| Feature | $push | $addToSet |
|---|---|---|
| Purpose | Add element to array | Add unique element to array |
| Duplicates Allowed? | Yes | No |
| Use Case | Append any value | Prevent duplicates |
| Performance | Faster for simple appends | Slightly slower due to uniqueness check |
| Supports Multiple Values | Yes, with $each | Yes, with $each |
| Behavior if Field Missing | Creates array with value | Creates array with value |
Key Differences
The $push operator in MongoDB simply appends the specified value to the end of an array field. It does not check if the value already exists, so duplicates can appear if you push the same value multiple times.
In contrast, $addToSet adds the value only if it is not already present in the array. This operator ensures the array behaves like a set, maintaining unique elements. Internally, MongoDB checks for the presence of the value before adding it.
Both operators can use the $each modifier to add multiple values at once. However, $addToSet will filter out duplicates among the new values and existing array elements, while $push will add all values regardless.
Code Comparison
Using $push to add values to an array:
db.users.updateOne(
{ _id: 1 },
{ $push: { hobbies: 'reading' } }
);
// Adding multiple values
db.users.updateOne(
{ _id: 1 },
{ $push: { hobbies: { $each: ['swimming', 'reading'] } } }
);$addToSet Equivalent
Using $addToSet to add unique values to an array:
db.users.updateOne(
{ _id: 1 },
{ $addToSet: { hobbies: 'reading' } }
);
// Adding multiple unique values
db.users.updateOne(
{ _id: 1 },
{ $addToSet: { hobbies: { $each: ['swimming', 'reading'] } } }
);When to Use Which
Choose $push when you want to add values to an array without caring about duplicates, such as logging events or maintaining order with repeated entries.
Choose $addToSet when you need to keep array elements unique, like storing tags, categories, or user IDs where duplicates are not allowed.
For performance-sensitive cases where duplicates are acceptable, $push is faster. For data integrity requiring uniqueness, $addToSet is the better choice.
Key Takeaways
$push adds values to arrays allowing duplicates.$addToSet adds values only if they are not already present.$push for simple appends and $addToSet to maintain unique arrays.$each.$addToSet has a slight performance cost due to uniqueness checks.