0

モーターモンゴカーソルの長さを決定する方法や、次があるかどうかを確認する方法はありますか (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

「生きている」プロパティを使用できます。これを実行してみてください:

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
于 2014-06-06T02:37:18.573 に答える