【问题标题】:How to get a single value from a pymongo query of a mongodb in python?如何从 python 中 mongodb 的 pymongo 查询中获取单个值?
【发布时间】:2013-02-25 13:05:35
【问题描述】:

我正在尝试使用 pymongo。到目前为止一切正常,我可以连接到 mongodb,插入和进行查询。我面临的问题是将数据从find() 获取到python 数组中。

这是我的代码

>>> 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 这样的东西?

【问题讨论】:

    标签: python arrays mongodb pymongo


    【解决方案1】:

    “bla”只是一个字典,所以

    myValues[i] = bla['value']
    

    就是你要找的。​​p>

    【讨论】:

      【解决方案2】:
      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-27
        • 2017-01-02
        • 2019-02-11
        • 2022-01-17
        • 2010-12-17
        • 1970-01-01
        • 2011-10-24
        相关资源
        最近更新 更多