Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load single field from pymongo as an array

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?

like image 859
Luke Sapan Avatar asked Nov 27 '25 06:11

Luke Sapan


1 Answers

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')
like image 98
JohnnyHK Avatar answered Nov 28 '25 20:11

JohnnyHK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!