0

请看下面的代码:

collection = db_name.get_db().collection_name
print collection
# prints .. Collection(Database(Connection('localhost', 27017), u'db_name'), u'colelction_name')


for key in some_dict.keys():
        query = {"p_id":key}
        document = collection.find(query)
        print document
        # gives <pymongo.cursor.Cursor object at 0x7f13f3049b10>

现在我想检索这个文档.. 并获取数据。但如果我这样做:

       for d in document:
            print d

我收到以下错误

    File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 703, in next
   if len(self.__data) or self._refresh():
 File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 666, in _refresh
self.__uuid_subtype))
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 628, in __send_message
self.__tz_aware)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/helpers.py", line 101, in _unpack_response
error_object["$err"])

我究竟做错了什么?谢谢

4

3 回答 3

1

您想检索“此文档” - 然后使用官方方法获取一个符合您的条件的文档:find_one():

http://api.mongodb.org/python/2.2/api/pymongo/collection.html

阅读基本 API 文档是您的朋友。

于 2012-05-02T04:10:05.330 回答
1

Also, note that pymongo has several constructor options availble to a cursor :

https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/cursor.py

Some of these options (await_data, exhaust, for example) will make a big difference in terms of speeding cursor iteration.

Depending on the length and complexity of your query, you can also process data in a separate thread, so that you run through the cursor as fast as possible, firing of asynchronous tasks along the way.

I've found that running a single thread for exhausting a mongo cursor, with separate threads for processing data from it can increase cursor throughput drastically, regardless of the amount of data the cursor brings down with it.

于 2012-09-14T21:55:04.427 回答
0

当 API 和 mongo 提供适合此的查询时,我不明白您为什么要尝试使用这种方法获取一批文档?

如果 some_dict.keys() 返回一个 id 列表,并且您想检索与这些 id 匹配的文档,为什么不使用正确的“in”查询?

docs = collection.find({'p_id': {'$in':some_dict.keys()}})
print docs
# <pymongo.cursor.Cursor object at 0x10112dfd0>
print [d for d in docs]
# [{DOC1}, {DOC2}, {...}]

As @ich recommended, the pymongo api docs explain everything, as well as reading the mongodb query language.

If this is not what you were looking for, then your intent was not clear in your question. It does simply look like you want to get a batch of documents matching a list of id's

于 2012-05-02T04:23:34.797 回答