Avoid duplicating values ​​when updating an array with $ push on MongoDB

I want to push some values ​​into an array using Python.
Perhaps the next time I update the array, it inserts some values, so it will get multiple duplicate values.
I want to know, one way or another, to avoid duplicate values.
Should I use db.collection.find () to determine if I should embed or not?

db.graph.insert_one({"user_id": a.url}, ) for j in a.followers: db.graph.update({"user_id": a.url}, {"$push": {"following": j.url}}) 
+5
source share
2 answers

The best way to do this is to use $addToSet , which ensures that no duplicate elements are added to the set, but $each to add multiple values ​​to the next array.

 urls = [j.url for j in a.followers] db.graph.update_one({"user_id": a.url}, {"$addToSet": {"following": {"$each": urls}}}) 

you should also use the update_one method because update deprecated.

+9
source

I think you can use the $ addToSet operator: https://docs.mongodb.org/manual/reference/operator/update/addToSet/

+3
source

Source: https://habr.com/ru/post/1246778/


All Articles