List comprehension with cursor from pymongo

旧时模样 提交于 2019-12-13 01:35:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!