【问题标题】:Iterate through PyMongo Cursor as key-value pair遍历 PyMongo 游标作为键值对
【发布时间】:2011-06-23 03:10:05
【问题描述】:

是否可以像 dict 这样将 pymongo Cursor 作为键值对进行迭代?我正在使用 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

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    试试:

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

    【讨论】:

      【解决方案2】:

      这是我用来从 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
      

      【讨论】:

      • 2 件事。 1) response = {} 会比json.loads('{}') 清晰得多。 2)你应该做for bp in cursor,因为你从enumerate()中忽略了idx
      猜你喜欢
      • 2019-08-22
      • 2019-04-10
      • 1970-01-01
      • 2018-02-19
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 2017-08-30
      • 2019-05-06
      相关资源
      最近更新 更多