Skip to content Skip to sidebar Skip to footer

List Comprehension With Cursor From Pymongo

Here is my pymongo code: client = MongoClient('localhost', 27017) db = client['somedb'] collection = db.somecollection return_obj = collection.find({'field1':'red'}) #First pri

Solution 1:

This is the correct behaviour, this is how it is supposed to be. Your variable return_obj is mongoDB cursor, which is a special class in python as described here. After using it once, the cursor is "exhausted".

Solution 2:

Imagine that the cursor object is a pointer (namely iterator), that points to the first item in return_obj. Each iteration you go through when using list comprehension (similarly to foreach iterations), that pointer points to the next item in the returned list. After looping through the whole list, the pointer just points to the end of the list. You can see it as an uncircular-linked-list. Thus, this cursor object is only one-time-use (I just lied, since you can reset it, but that's best for your understanding).

Wish it helps.

Post a Comment for "List Comprehension With Cursor From Pymongo"