简体   繁体   中英

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 print statement
print([item['field1'] for item in return_obj])

#Second print statement
print([item['field1'] for item in return_obj])

The first print statement produces non-empty list, while the second one produces empty list. As if I have to reset an index on return_obj.

Any ideas?

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".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM