Search code examples
mongodb

MongoDb: Difference between $push/$addtoset


I read the documentation in the MongoDb and I used a simple proves and I only look that: Push is sorting the array but addtoSet isn't it.

For me visually is the same, I don't know the difference.

Could anybody explain me the difference?

Another think if it could be in spanish or in a simple english, i'll aprecite it.


Solution

  • $addToSet do not add the item to the given field if it already contains it, on the other hand $push will 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: {items:2}}); // this will update the document. new document {_id: "docId", items:[1,2,2]}