pythonmongodbmongodb-querypymongo

Avoid a duplicate value when I update array using $push on MongoDB


I want to push some values into array using Python.
Maybe next time when i update the array ,it will insert some values exists ,so it will got some duplicate values.
I want to know is there anyway to avoid duplicate values.
Should I use db.collection.find() to determine whether I should insert 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}})

Solution

  • The best way to do this is using $addToSet operator which ensures that there are no duplicate items added to the set and the $each modifier to add multiple values to the"following" array.

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

    also you should use the update_one method because update is deprecated.