【问题标题】:How to continue reading a Mongodb cursor?如何继续读取 Mongodb 游标?
【发布时间】:2013-11-17 23:53:23
【问题描述】:

在这个简化的示例中,我有一个返回 10 个文档的查询。

我想先将前半部分 (n = 5) 还给我的客户。如果他想继续阅读,他可以提交请求,我将下半部分还给他(n = 5)

在 pyMongo 中:

doc = collection.find({'foo': 'bar'}).limit(10)

一种不太聪明的方法,IMO,我可以将 doc 光标一分为二,给我的客户doc[:4],然后根据要求给他doc[5:]

这是最好的方法吗?是否有任何方法可以返回我离开的位置,并允许我回来阅读其余的文档?

【问题讨论】:

  • 您可以将 .skip() 方法用于小型集合。如果不提供其他信息如何存储数据(它们是否已排序,索引是什么?),很难提出最佳方法。

标签: python mongodb pymongo


【解决方案1】:

有什么理由不使用pymongo.cursor.Cursor.next 方法吗?

try:
    c = collection.find({'foo': 'bar'}).limit(10)

    # Take first five
    for in range(5):
        doc = c.next()

    #If you need more
    for in range(5):
        doc = c.next()

 # If there is no next
 except StopIteration:
     pass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    相关资源
    最近更新 更多