简体   繁体   English

如何从python中的mongodb的pymongo查询中获取单个值?

[英]How to get a single value from a pymongo query of a mongodb in python?

I'm trying to use pymongo. 我正在尝试使用pymongo。 Everything is ok so far, I can connect to mongodb, insert and make queries. 到目前为止一切都还可以,我可以连接到mongodb,插入并进行查询。 The problem i'm facing is getting data from find() into a python array. 我面临的问题是将find()数据转换为python数组。

This is my code 这是我的代码

>>> a = db.sensor.find({'sensor_id':3})
>>> a
<pymongo.cursor.Cursor object at 0x637f70>
>>> for bla in a:
...     print bla
... 
{u'date': datetime.datetime(2013, 3, 4, 21, 8, 23, 907000), u'_id': ObjectId('51350d4772ab8a691c370453'), u'sensor_id': 3, u'value': -1625.0}
{u'date': datetime.datetime(2013, 3, 4, 21, 20, 12, 694000), u'_id': ObjectId('5135100c72ab8a695b54a4f3'), u'sensor_id': 3, u'value': -1875.0}
{u'date': datetime.datetime(2013, 3, 4, 21, 22, 4, 985000), u'_id': ObjectId('5135107c72ab8a69851a5a95'), u'sensor_id': 3, u'value': -1812.0}
{u'date': datetime.datetime(2013, 3, 4, 21, 26, 11, 758000), u'_id': ObjectId('5135117372ab8a69b285b4c7'), u'sensor_id': 3, u'value': -1312.0}

Is there a way to make something like myValues[i] = bla.value ? 有没有办法制作类似myValues[i] = bla.value

The "bla" is just a dictionary, so “bla”只是一本字典,所以

myValues[i] = bla['value']

is what you are looking for. 是你在找什么。

a = db.sensor.find({'sensor_id':3})
#your values are in dictionary format..
for key, val in a.items():
     print(val)

if you want particular column value, try this.. 如果你想要特定的列值,试试这个..

a = db.sensor.find({'sensor_id':3})
#your values are in dictionary format..
for key, val in a.items():
    if 'date' in key:
       print(val) #now you got only date column values

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM