是否可以将pymongo Cursor
作为键值对迭代,如dict
?我正在使用python 2.6和pymongo 1.9。
我试过这个:
import pymongo
mongo = pymongo.Connection('localhost')
mongo_db = mongo['my_database']
mongo_coll = mongo_db['my_collection']
cursor = mongo_coll.find()
records = dict([(record_id, record) for record_id, record in mongo_cursor])
但我收到错误:
ValueError: too many values to unpack
答案 0 :(得分:17)
尝试:
records = dict((record['_id'], record) for record in cursor)
答案 1 :(得分:-1)
这是python中的一个函数,我用它来构建一个来自MongoDB游标的JSON响应
def build_contacts_cursor(cursor):
''' Builds a JSON response for a given cursor
'''
response = json.loads('{}')
response_to_append_to = response['results'] = []
for idx, bp in enumerate(cursor):
response_to_append_to.append(bp)
return response