从Pymongo查询获取字符串数组 [英] Get string array from Pymongo query

查看:353
本文介绍了从Pymongo查询获取字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从"colname"字段获取一个包含值的数组.我不能返回游标,只能返回值数组.

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.

现在我正在这样做:

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

然后我返回entomo_array.

推荐答案

如果"colname"字段具有不同的值,或者如果您不关心重复的值,则可以使用不同的功能.例如:

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

这篇关于从Pymongo查询获取字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆