Get string array from Pymongo query

核能气质少年 提交于 2019-12-13 21:29:34

问题


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.


回答1:


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')



回答2:


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')


来源:https://stackoverflow.com/questions/43079206/get-string-array-from-pymongo-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!