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.
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):
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.