Is it possible to iterate over a pymongo Cursor
as a key-value pair like a dict
? I'm using python 2.6 and pymongo 1.9.
I've tried this:
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])
But I get the error:
ValueError: too many values to unpack
尝试:
records = dict((record['_id'], record) for record in cursor)
this is a fuction in python I used to build a JSON response from a MongoDB cursor
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.