「生きている」プロパティを使用できます。これを実行してみてください:
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)
最終文書までは「真」、生きている場合は「偽」を出力します。
MotorCursor は、サーバーからバッチでデータを取得します。(バッチに関する MongoDB のドキュメントでは、Motor を含むすべての MongoDB ドライバーでカーソルとバッチがどのように機能するかについて説明しています。) "alive" が True の場合、サーバーに利用可能なデータが他にもあること、データが MotorCursor にバッファーされていること、またはその両方であることを意味します。 .
ただし、競合状態があります。最終的なドキュメント以外をすべて取得し、その最後のドキュメントを取得する前に別のクライアントがそれを削除すると、「生きている」が「真」であったとしても、最後のドキュメントを見つけることができないとします。ループを再配置することをお勧めします:
@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