Using a generator to iterate over a large collection in Mongo
我有一个包含 500K 文档的集合,这些文档存储在单个节点 mongo 上。我的 pymongo cursor.find() 时不时会因为超时而失败。
虽然我可以将 find 设置为忽略超时,但我不喜欢这种方法。相反,我尝试了一个生成器(改编自这个答案和这个链接):
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def mongo_iterator(self, cursor, limit=1000):
skip = 0 while True: results = cursor.find({}).sort(“signature”, 1).skip(skip).limit(limit) try: except StopIteration: for result in results: skip += limit |
然后我使用以下方法调用此方法:
1
2 3 |
ref_results_iter = self.mongo_iterator(cursor=latest_rents_refs, limit=50000)
for ref in ref_results_iter: results_latest1.append(ref) |
问题:
我的迭代器不会返回相同数量的结果。问题是 next() 使光标前进。所以每次通话我都会失去一个元素…
问题:
有没有办法调整这段代码,以便我可以检查下一个是否存在? Pymongo 3x 不提供 hasNext() 并且 ‘alive’ 检查不保证返回 false。
- 0 to 1000 等于 [0,1,2,3……,999],下一个开始是 1000 但你会失去一个(可能是 last_one)。所以 index number never equal to length_number。
- 说 first_result_in_batch = results.next() 是否有效,从而捕获您当前丢弃的元素(如果有)?然后将 yield first_result_in_batch 放在 for 循环之上,从而以正确的顺序将该元素提供给调用者。 (我不知道 MongoDB,所以也许我遗漏了一些东西。)
.find() 方法采用额外的关键字参数。其中之一是 no_cursor_timeout 您需要将其设置为 True
1
|
cursor = collection.find({}, no_cursor_timeout=True)
|
您不需要编写自己的生成器函数。 find() 方法返回一个类似 object.
的生成器
为什么不使用
1
2 |
for result in results:
yield result |
for 循环应该为你处理 StopIteration。
- 它确实停止了,但我需要知道并处理迭代
来源:https://www.codenong.com/39606506/