python motor mongo cursor length or peek next
Question: is there a way of determining the length of the motor mongo cursor or peeking
ahead to see if there is a next ( instead of `fetch_next` perhaps `has_next` )

and not the `cursor.size()` that does not take into the provided limit()

basically i desire to add the required json comma

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


Answer: You can use the "alive" property. Try running this:

    
    
    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)
    

It prints "True" until the final document, when alive is "False".

A MotorCursor fetches data from the server in batches. ([The MongoDB
documentation on batches](http://docs.mongodb.org/manual/core/cursors/#cursor-
batches) explains how cursors and batches work for all MongoDB drivers,
including Motor.) When "alive" is True it means either that there is more data
available on the server, or data is buffered in the MotorCursor, or both.

There is a race condition, however. Say that you fetch all but the final
document, and before you fetch that last document another client deletes it,
then you'll fail to find the last document even though "alive" was "True".
Better to rearrange your loop:

    
    
    @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
    

