使 Mongodb/pymongo 查询立即开始执行,而不是等待第一次迭代

问题描述 投票:0回答:1
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!

注意:我不想立即获取所有文档,只需获取第一个文档/一批文档以避免延迟加载。

mongodb pymongo
1个回答
0
投票

您可以在创建光标后立即尝试使用

hasNext

cursor = coll.find(query, sort=sort)
cursor.hasNext()
如果迭代器中有文档,

hasNext
将返回 true,否则返回 false。关键是它必须咨询服务器,从而获得第一批结果,然后才能返回。

请注意,

hasNext
将阻塞,直到有答案为止。

© www.soinside.com 2019 - 2024. All rights reserved.