Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push an element to an array if it is not present (no duplicates)

Tags:

python

mongodb

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.

like image 946
Ms01 Avatar asked Jun 13 '12 14:06

Ms01


People also ask

How do you push an object to an array without 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.

How do you return an array without duplicates?

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.

How do you push an element to an empty array?

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

How do you push an element to an array?

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.


1 Answers

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.

like image 165
Ms01 Avatar answered Sep 24 '22 23:09

Ms01