使用生成器迭代 Mongo 中的大型集合

gog*_*elj 5 python mongodb pymongo pymongo-3.x

我有一个包含 500K+ 文档的集合,这些文档存储在单个节点 mongo 上。我的 pymongo cursor.find() 时不时会因为超时而失败。

虽然我可以设置find忽略超时,但我不喜欢这种方法。相反,我尝试了一个生成器(改编自这个答案和这个链接):

def mongo_iterator(self, cursor, limit=1000):
        skip = 0
        while True:
            results = cursor.find({}).sort("signature", 1).skip(skip).limit(limit)

            try:
                results.next()

            except StopIteration:
                break

            for result in results:
                yield result

            skip += limit
Run Code Online (Sandbox Code Playgroud)

然后我使用以下方法调用此方法:

ref_results_iter = self.mongo_iterator(cursor=latest_rents_refs, limit=50000)
for ref in ref_results_iter:
    results_latest1.append(ref)
Run Code Online (Sandbox Code Playgroud)

问题:我的迭代器没有返回相同数量的结果。问题是 next() 使光标前进。所以每次通话我都会失去一个元素......

问题:有没有办法调整这段代码,以便我可以检查下一个是否存在?Pymongo 3x 不提供 hasNext() 并且 'alive' 检查不保证返回 false。

Pat*_*ugh 1

为什么不使用

for result in results:
    yield result
Run Code Online (Sandbox Code Playgroud)

for 循环应该可以StopIteration为你处理。