I have an event collection which I'm going through to find a category to the specific event and then I'm updating my other collection using a $push statement. The problem is that when two events have the same category it'll create a duplicate, which I don't want.
I know about upserts but I am unsure if they are the best way to go regarding this? And I'm a bit confused when it comes to how to actually write an upsert that works with the "$push"-statement.
This is how my update looks right now:
self.users.update({"user_id": event['userid']}, {'$push': {'campaigns': UserCampaign}})
..where:
UserCampaign = {
"id": campaign['id'],
"name": campaign['name']
}
The "UserCampaign" gets filled up with the same information from time to time, and since my collection is probably gonna be very huge I want to complete this as efficient as possible.
TLDR; I want to update the array in the document found using a "push" without having the risk of getting duplicates.
To prevent adding duplicates to an array:Use the Array. includes() method to check if the value is not present in the array. If the value is not present, add it to the array using the push() method. The array will not contain any duplicate values.
Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.
When you want to add an element to the end of your array, use push() . If you need to add an element to the beginning of your array, use unshift() . If you want to add an element to a particular location of your array, use splice() .
JavaScript Array push()The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.
Found a better answer to my problem:
By using $addToSet it didn't create duplicates (I also made sure no duplicates where made before by adding all dictionaries to a list):
self.users.update({"user_id": event['userid']}, {'$addToSet': {'campaigns': UserCampaigns[i]}})
If I just had used $push it would always create duplicate elements in 'campaigns' within the users collection. This happened with and without upsert.
For some reason $each didn't work but wasn't required, I guess PyMongo takes care of that for me.
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