【问题标题】:Get a list of documents while iterating through mongodb cursor遍历mongodb游标时获取文档列表
【发布时间】:2014-10-23 06:42:56
【问题描述】:

是否可以在遍历 mongodb 游标时检索文档列表?我的意思是:

for item in collection.find():
    # do stuff with the document

Item 只是一个文档,但我能以某种方式检索一个列表并继续遍历光标吗? (因为collection.find()[:2] 返回一个列表,但您无法保留光标)。我知道我可以使用一些计数器来做到这一点,但是有语法糖吗?

看起来游标可以像列表一样被压缩:

for item1, item2 in zip(collection.find(), collection.find({'_id': {'$gt': 0}})):
    print((item1, item2))

编辑: 在this solution 中显示,您可以将整个集合作为一个列表(如果它适合 RAM)并遍历它。这适合我的用例,但如果它不适合 RAM 怎么办?

【问题讨论】:

  • 如果您觉得答案有帮助,请随时点赞和/或接受它

标签: mongodb pymongo


【解决方案1】:

您可以在this question 的答案中使用任何滚动窗口生成器,并将其应用于光标。例如

cursor = collection.find()
for doc1, doc2 in window(cursor, n=2):
    print(doc1, doc2)

或者

for doc1, doc2, doc3 in window(cursor, n=3):
    print(doc1, doc2, doc3)

等等

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 2018-03-06
    相关资源
    最近更新 更多