coll = MongoClient(uri)[database][collection]
cursor = coll.find(query, sort=sort) # I want the query to start executing here!
# It doesnt matter to my application if we're stuck here for a couple seconds
# ...
doc = next(cursor) # this must not be slow!
Note: I dont want to fetch all documents right away, just get the first document/batch of documents to avoid the lazy loading.
2
Answers
You might try using
hasNext
immediately after creating the cursor.hasNext
will return true if there is a document in the iterator, false if not. The point is that it must consult the server, and therefore get the first batch of results, before it can return.Note that
hasNext
will block until an answer is available.Here’s how you could so it; set up a class which gets the first item in the cursor. Then use a generator to yield the first item then the remaining items in a cursor:
In a worked example with some random data:
prints: