2013-03-10 67 views
1

我正在嘗試使用pymongo。一切都很好,我可以連接到MongoDB,插入和查詢。我面臨的問題是從find()獲取數據到python數組中。如何從python中的mongodb的pymongo查詢中獲取單個值?

這是我的代碼

>>> 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} 

有沒有一種方法,使像myValues[i] = bla.value

回答

8

的「喇嘛」僅僅是一個字典,所以

myValues[i] = bla['value'] 

是你在找什麼。

+0

哇...謝謝! – otmezger 2013-03-10 08:45:17

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

如果你想要特定的列值,試試這個..

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 
相關問題