0
0
MongodbComparisonBeginner · 4 min read

$push vs $addToSet in MongoDB: Key Differences and Usage

In MongoDB, $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
PurposeAdd element to arrayAdd unique element to array
Duplicates Allowed?YesNo
Use CaseAppend any valuePrevent duplicates
PerformanceFaster for simple appendsSlightly slower due to uniqueness check
Supports Multiple ValuesYes, with $eachYes, with $each
Behavior if Field MissingCreates array with valueCreates 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:

mongodb
db.users.updateOne(
  { _id: 1 },
  { $push: { hobbies: 'reading' } }
);

// Adding multiple values

db.users.updateOne(
  { _id: 1 },
  { $push: { hobbies: { $each: ['swimming', 'reading'] } } }
);
Output
{ "acknowledged" : true, "modifiedCount" : 1 }
↔️

$addToSet Equivalent

Using $addToSet to add unique values to an array:

mongodb
db.users.updateOne(
  { _id: 1 },
  { $addToSet: { hobbies: 'reading' } }
);

// Adding multiple unique values

db.users.updateOne(
  { _id: 1 },
  { $addToSet: { hobbies: { $each: ['swimming', 'reading'] } } }
);
Output
{ "acknowledged" : true, "modifiedCount" : 1 }
🎯

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.
Use $push for simple appends and $addToSet to maintain unique arrays.
Both support adding multiple values with $each.
$addToSet has a slight performance cost due to uniqueness checks.