Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}})
like image 637
Tracy Da Avatar asked Apr 09 '16 15:04

Tracy Da


People also ask

How do you prevent duplicates in MongoDB?

To insert records in MongoDB and avoid duplicates, use “unique:true”.

How do you prevent duplicate arrays?

To prevent adding duplicates to an array:Use the indexOf() method to check that the value is not present in the array. The indexOf method returns -1 if the value is not contained in the array. If the condition is met, push the value to the array.

How do you update an array element in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.

How do I remove duplicates in MongoDB?

Ad. Remove Duplicate Documents: MongoDB. We learnt how to create unique key/index using {unique: true} option with ensureIndex() method. Now lets see how we can create unique key when there are duplicate entries/documents already present inside the collection.


2 Answers

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.

like image 110
styvane Avatar answered Sep 19 '22 20:09

styvane


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

like image 23
Aleksandr Karasev Avatar answered Sep 20 '22 20:09

Aleksandr Karasev