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 Cu
Solution 1:
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')
Solution 2:
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')
Post a Comment for "Get String Array From Pymongo Query"