Along side the differences that others have mentioned
$push
: Appends an object to an array
$addToSet
: Adds an object to an array if it does not exists
There is a difference in replication. (This can be seen if by taking a look at local.oplog.rs
)
$push
operations (that actually modified the array) are replicated as $set.items.INDEX: item
$addToSet
operations (that actually modified the array) are replicated as $set.items: [THE_ENTIRE_ARRAY]
If you are dealing with large arrays, then the difference might be significant
So while something like (the typical use case to maintain unique array)
db.items.updateOne(
{_id: 'my-id', 'items': {'$ne': 'items1'},
{'$push': {
'items': 'item1',
}}
)
db.items.updateOne(
{_id: 'my-id'},
{'$addToSet': {
'items': 'item1',
}}
)
might end up with the same resulting document, there is a difference in the replicated operation.