0

有没有办法确定电机 mongo 光标的长度或向前看是否有下一个(而不是fetch_next也许has_next

而不是cursor.size()不考虑提供的 limit()

基本上我希望添加所需的 json 逗号

        while (yield cursor.fetch_next):
           document =  cursor.next_object()
           print document
           if cursor.has_next() # Sweeet
               print ","
4

1 回答 1

1

您可以使用“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
于 2014-06-06T02:37:18.573 回答