简体   繁体   中英

Get all documents from mongo collection using a nested list comprehension in Python

I have a python list of mongo documents called id_list which contains a field called userId , and a mongo collection of user transactions called collection . I want to retrieve all the transactions in the collection for each user by passing the id of each user in id_list as a parameter to the mongo query inside a nested list comprehension.

This is what i tried:

[doc for doc in collection.find({'userId': user._id, 'site': SITE, 'operator': OPERATOR, 'isTrue': {'$exists': True}}) for user in [user for user in id_list]]

It looked correct for me but when i run this it returns an empty list which is impossible.

If i try this:

[doc in collection.find({'userId': user._id, 'site': SITE, 'operator': OPERATOR, 'isTrue': {'$exists': True}}) for user in [user for user in id_list]]

I get a list containing a single transaction for each user, but i want to recover all the transactions for each user i pass from the ´id_list´.

Could someone please tell me what's wrong with the list comprehension?

Thank you very much in advance.

I finally got it by doing this:

[doc for doc in collection.find({'userId': {'$in': id_list}, 'site': SITE, 'operator': OPERATOR, 'isTrue': {'$exists': True}})]

Instead of passing each id in the list one by one to the mongo query, i used the $in operator, and passed it the id_list there. Appart of being the correct way to do this, it's also way more efficient than what i was trying since the id_list is being looped inside the mongo query and not in Python.

Thanks anyway:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM