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.
The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array. The $addToSet operator has the form: { $addToSet: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.
If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.
To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
$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]}
$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 guaranteed.
If you need to add unique items in order, you can group and add elements via $addToSet, then $unwind the array with elements, $sort by items, and then do $group again with $push items.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With