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

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]}



About Mohammad Fareed

Software Engineer @ Tekzenit.

Check Also

Scientist Finds Breakthrough Weight Loss Formula!

Don’t act so surprised, Your Highness. You weren’t on any mercy mission this time. Several …

Leave a Reply

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