I have a list of mongo objects that I basically want to pluck a single field from.
So let's say my objects are structured like this
[
{'name': 'Lucy', age: '24'},
{'name': 'Nicole', age: '22'},
{'name': 'John', age: '28'},
]
I want to load an array from PyMongo in the format ['Lucy', 'Nicole', 'Lauren'].
One way to do this is just a simple python list comprehension:
names = [p['name'] for p in db.people.find({'age': {'$gt': 18}}, ['name'])]
That works fine, but if there are a lot of records it's very slow. Is there a more efficient way of doing this?
As long as you don't need to include duplicates, you can do this by calling distinct on the cursor returned by your find query:
names = db.people.find({'age': {'$gt': 18}}).distinct('name')
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