AFP_555
AFP_555

Reputation: 2608

Get string array from Pymongo query

I need to get an array with the values from the field 'colname'. I can't return a Cursor, just the array of values.

Is there a way to query this array without having to loop the Cursor? I feel this is a waste of processing resources.

Right now I'm doing this:

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
headers = client['headers']

entomo = headers.entomo

entomo_data = entomo.find()
entomo_array = []
for data in entomo_data:
    entomo_array.append(data['colname'])

Then I return the entomo_array.

Upvotes: 0

Views: 981

Answers (2)

Sede
Sede

Reputation: 61273

You can do this with the .aggregate() method by $grouping your documents by None

cursor = entomo.aggregate([
    {'$group': {
        '_id': None, 
        'data': {'$push': '$colname'}
    }}
])

From there, you simply consume the cursor using next.

entomo_array = next(cursor)['data']

But if 'colname' is unique within the collection, you can simply use the the distinct method.

entomo_array = entomo.distinct('colname')

Upvotes: 1

Moi Syme
Moi Syme

Reputation: 466

If the 'colname' field has distinct values or if you do not care about duplicate values you can use distinct function. For your example:

entomo_array = entomo.find().distinct('colname')

Upvotes: 0

Related Questions