问题
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 $group
ing 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