13

是否可以将 pymongoCursor作为键值对进行迭代,例如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
4

2 回答 2

17

尝试:

records = dict((record['_id'], record) for record in cursor)
于 2011-02-08T00:49:21.340 回答
-1

这是我用来从 MongoDB 游标构建 JSON 响应的 python 功能

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
于 2015-03-09T01:24:33.813 回答