def fetch_next(self):
"""A Future used with `gen.coroutine`_ to asynchronously retrieve the
next document in the result set, fetching a batch of documents from the
server if necessary. Resolves to ``False`` if there are no more
documents, otherwise :meth:`next_object` is guaranteed to return a
document.
.. _`gen.coroutine`: http://tornadoweb.org/en/stable/gen.html
.. testsetup:: fetch_next
MongoClient().test.test_collection.remove()
collection = MotorClient().test.test_collection
.. doctest:: fetch_next
>>> @gen.coroutine
... def f():
... yield collection.insert([{'_id': i} for i in range(5)])
... cursor = collection.find().sort([('_id', 1)])
... while (yield cursor.fetch_next):
... doc = cursor.next_object()
... sys.stdout.write(str(doc['_id']) + ', ')
... print 'done'
...
>>> IOLoop.current().run_sync(f)
0, 1, 2, 3, 4, done
.. note:: While it appears that fetch_next retrieves each document from
the server individually, the cursor actually fetches documents
efficiently in `large batches`_.
.. _`large batches`: http://docs.mongodb.org/manual/core/read-operations/#cursor-behaviors
"""
future = Future()
if not self._buffer_size() and self.alive:
if self._empty():
# Special case, limit of 0
future.set_result(False)
return future
def cb(batch_size, error):
if error:
future.set_exception(error)
else:
future.set_result(bool(batch_size))
self._get_more(cb)
return future
elif self._buffer_size():
future.set_result(True)
return future
else:
# Dead
future.set_result(False)
return future
评论列表
文章目录