What is the difference between $push and $addtoset in mongo db

$addToSet do not add the item to the given field if it already contains it,

on the other hand, $pushwill add the given object to field whether it exists or not.

{_id: "docId",
 items: [1, 2]}

db.items.update({_id:"docId"}, {$addToSet:{items: 2}}); // This won't update the document as it already contains 2
db.items.update({_id:"docId"}, {$push: {item:2}}); // this will update the document. new document {_id: "docId", items:[1,2,2]}




Source: 

https://stackoverflow.com/questions/27248556/mongodb-difference-between-push-addtoset

Add a Comment

Your email address will not be published. Required fields are marked *