如何访问查询字段

时间:2016-04-07 22:26:04

标签: python mongodb

我有一个来自此代码的查询

cursor = db.MCAddrPortPairs.find({'Symbol' : symbol})[:1]
print str(json.dumps({'results': list(cursor)},
                        default = bson.json_util.default,
                        indent = 4))

返回以下文档:

{
    "results": [
        {
            "MCPort": 345, 
            "Symbol": "EUR/USD", 
            "_id": {
                "$oid": "56fc34e961fed32064e656b0"
            }, 
            "MCAddr": "239.0.0.222"
        }
    ]
}

MCAddr是一个字符串,MCPort是一个int。如何在python中访问字段MCAddr和MCPort?

编辑1

如果我说

doc = db.MCAddrPortPairs.find({'Symbol' : symbol})[:1]

symbolMCIPAddrStr = doc["MCAddr"]
symbolMCPort = doc["MCPort"]

我收到错误:

File "mc.py", line 44, in initializeMongo
    symbolMCIPAddrStr = doc["MCAddr"]
  File "/home/idf/anaconda/lib/python2.7/site-packages/pymongo/cursor.py", line 531, in __getitem__
    self.__check_okay_to_chain()
  File "/home/idf/anaconda/lib/python2.7/site-packages/pymongo/cursor.py", line 342, in __check_okay_to_chain
    raise InvalidOperation("cannot set options after executing query")
pymongo.errors.InvalidOperation: cannot set options after executing query

编辑2

如果相反,我说

doc = db.MCAddrPortPairs.find_one({'Symbol' : symbol})[:1]


Traceback (most recent call last):
  File "mc.py", line 86, in <module>
    main()
  File "mc.py", line 63, in main
    initializeMongo("EUR/USD") 
  File "mc.py", line 39, in initializeMongo
    doc = db.MCAddrPortPairs.find_one({'Symbol' : symbol})[:1]
TypeError: unhashable type

1 个答案:

答案 0 :(得分:2)

您可以访问游标返回的文档,无需将结果转储到JSON中。如果只需要一份文件,我也会使用find_one()

doc = db.MCAddrPortPairs.find_one({'Symbol' : symbol})
port, address = doc["MCPort"], doc["MCAddr"]
print(port, address)