Iterate through PyMongo Cursor as key-value pair
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 ma开发者_如何学Gony values to unpack
Try:
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
精彩评论