Both $push and $addToSet are update operators in MongoDB which are used to add new elements to an array field. However, the key difference between these two update operators is how they handle inserting new elements into an array field.
The $push operator adds a specified value to an array field, even if it already exists in the array. If the specified value is an array itself, $push inserts the entire array as a single element of the main array. The syntax for using $push is as follows:
db.collection.update(
<query>,
{ $push: { <field>: <value> } },
{ <options> }
)
Here, β<field>β is the array field to which the value is being pushed and β<value>β is the value being pushed. For example, consider the following query:
db.myCollection.update({"_id": ObjectId("5ea1ad2e284b54a77bcc97a4")}, {$push: {"scores": 80}})
This query finds a document with the specified β_idβ and adds the value 80 to the βscoresβ array, even if the array already contains the value 80.
On the other hand, the $addToSet operator adds a specified value to an array field only if it does not already exist in the array. If the specified value is an array itself, $addToSet checks if any element in the array already exists in the main array and only adds the entire array as a single element if none of its elements already exists. The syntax for using $addToSet is as follows:
db.collection.update(
<query>,
{ $addToSet: { <field>: <value> } },
{ <options> }
)
Here, β<field>β is the array field to which the value is being added and β<value>β is the value being added. For example, consider the following query:
db.myCollection.update({"_id": ObjectId("5ea1ad2e284b54a77bcc97a4")}, {$addToSet: {"scores": 80}})
This query finds a document with the specified β_idβ and adds the value 80 to the βscoresβ array only if it does not already exist in the array.
To summarize, while both operators perform similar tasks of adding elements to an array field, the $push operator adds the element even if it already exists, while the $addToSet operator adds the element only if it does not already exist in the array.