MongoDb: Difference between $push/$addtoset

2019-01-23 10:31发布

问题:

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.

回答1:

$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: {item:2}}); // this will update the document. new document {_id: "docId", items:[1,2,2]}


回答2:

$push - adds items in the order in which they were received. Also you can add same items several times

$addToSet - adds just unique items, but order of items is not guarantied

In case if you need to add unique items ordered, you can group and add elements via $addToSet, then $unwind array with elements, $sort by items, and then do $group again with $push items.



回答3:

$addToSet and $push does the same thing, however $push just pushes any item disregarding the duplication causing redundancy. The former pushes only unique items, no duplication.



回答4:

As the name suggest $addToSet (set) wont allow duplicates while $push simply add the element to array



回答5:

$push: Inserts the value to an array in the resulting document. eg;

db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])

$addToSet: Inserts the value to an array in the resulting document but does not create duplicates. eg;

db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])


标签: mongodb