Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I read the documentation in the MongoDb and I used a simple proof 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 to me the difference?

Another thing if it could be in Spanish or in simple English, I’ll appreciate it.

2 Answers

0 votes
by (106k points)

The difference between $push/$addtoset is the $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}}); 

db.items.update({_id:"docId"}, {$push: {item:2}}); 

+1 vote
by (107k points)

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

$addToSet - adds just unique items, but the order of items is not guaranteed.

If you want to add unique items in the order, you can group and add elements with the help of $addToSet, then $unwind the array with elements, $sort by items, and then do $group again with $push items.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...