Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb: Difference between $push/$addtoset

Tags:

mongodb

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.

like image 840
Emilio López Avatar asked Dec 02 '14 11:12

Emilio López


People also ask

How do you use $addToSet?

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.

How does push work in MongoDB?

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.

How do I push an element to an array in MongoDB?

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.

How do you delete an element from an array in MongoDB?

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.


2 Answers

$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]} 
like image 180
cubbuk Avatar answered Sep 19 '22 11:09

cubbuk


$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.

like image 31
Oleksandr Lukichov Avatar answered Sep 16 '22 11:09

Oleksandr Lukichov