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!
注意:我不想立即获取所有文档,只需获取第一个文档/一批文档以避免延迟加载。
您可以在创建光标后立即尝试使用
hasNext
。
cursor = coll.find(query, sort=sort)
cursor.hasNext()
如果迭代器中有文档,hasNext
将返回 true,否则返回 false。关键是它必须咨询服务器,从而获得第一批结果,然后才能返回。
请注意,
hasNext
将阻塞,直到有答案为止。