2011-02-08 16 views
13

のように、pymongo Cursorをキーと値のペアとして反復処理できますか?私はPython 2.6とpymongo 1.9を使用しています。PyMongo Cursorをキーと値のペアとして反復処理します

私はこれ試してみた:

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 

答えて

15

試してみてください。これは私が構築するために使用するPythonでのfuctionがある

records = dict((record['_id'], record) for record in cursor) 
-1

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 
+0

2つのもの。 1) 'response = {}'は 'json.loads( '{}')'よりはるかに明確です。 2) 'enumate()'から 'idx'を無視しているので、' for bp in cursor'を実行する必要があります。 – cpburnz

関連する問題