Find dict in array without knowing the index mongodb

Viewed 21

I have a MongoDB document with an array called forms, inside the array each item is a dictionary, there are a couple of documents in this format, each document has an email field for user identification, and each dictionary has an identifier called title. My question is how do I check if a specific dictionary is inside the array using the title parameter and retrieve the index, and how do I ensure that I will find the item in the current user document?

Thanks

1 Answers

Ok after some research I found a way:

def already_exists(self, new_form, email):
    raw_idx = list(self.users_data_collection.aggregate(
        [
            {'$match': {'email': email}},
            {'$project': {
                'index': {'$indexOfArray':['$forms.title',new_form['title']]}
            }
            }
        ]
    )
    )
    return raw_idx[0]['index']

I filtered it with the email param to find the correct document and the raw_idx return list of dict which contains the _id field and index field, and then i\I returned the index only.

I hope I have helped someone in need.

Related