问题
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?
回答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".
回答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.
来源:https://stackoverflow.com/questions/31213115/list-comprehension-with-cursor-from-pymongo