您可以使用“alive”属性。尝试运行这个:
from tornado import gen, ioloop
import motor
client = motor.MotorClient()
@gen.coroutine
def f():
collection = client.test.collection
yield collection.drop()
yield collection.insert([{'_id': i} for i in range(100)])
cursor = collection.find()
while (yield cursor.fetch_next):
print cursor.next_object(), cursor.alive
ioloop.IOLoop.current().run_sync(f)
它打印“True”直到最终文档,当活着时为“False”。
MotorCursor 从服务器批量获取数据。(关于批处理的 MongoDB 文档解释了游标和批处理如何适用于所有 MongoDB 驱动程序,包括 Motor。)当“alive”为 True 时,意味着服务器上有更多可用数据,或者数据在 MotorCursor 中缓冲,或两者兼而有之.
但是,有一个竞争条件。假设您获取除了最终文档之外的所有文档,并且在您获取最后一个文档之前另一个客户端将其删除,那么即使“alive”为“True”,您也将无法找到最后一个文档。最好重新排列你的循环:
@gen.coroutine
def f():
collection = client.test.collection
yield collection.drop()
yield collection.insert([{'_id': i} for i in range(100)])
cursor = collection.find()
if (yield cursor.fetch_next):
sys.stdout.write(str(cursor.next_object()))
while (yield cursor.fetch_next):
sys.stdout.write(", ")
sys.stdout.write(str(cursor.next_object()))
print