iterating over mongo document in python

By : Fraz

Please take a look at the following code:

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>

Now I want to retreive this document.. and fetch the data. but if i do:

       for d in document:
            print d

I get the following error

    File "/usr/local/lib/python2.7/dist-packages/pymongo/", line 703, in next
   if len(self.__data) or self._refresh():
 File "/usr/local/lib/python2.7/dist-packages/pymongo/", line 666, in _refresh
  File "/usr/local/lib/python2.7/dist-packages/pymongo/", line 628, in __send_message
  File "/usr/local/lib/python2.7/dist-packages/pymongo/", line 101, in _unpack_response

What am i doing wrong? Thanks

By : Fraz


I don't understand why you are trying to get a batch of documents using this approach, when the API and mongo provides queries to suit this?

If some_dict.keys() returns a list of id's, and you want to retrieve the documents matching those id's, why not use a proper "in" query?

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

By : jdi

You want to retrieve "this document" - then use the official method for fetching one document matching your criteria: find_one():

Reading basic API documentation is your friend.

This video can help you solving your question :)
By: admin