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}})
To insert records in MongoDB and avoid duplicates, use “unique:true”.
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.
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.
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.
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.
I think, that you can use $addToSet operator: https://docs.mongodb.org/manual/reference/operator/update/addToSet/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With