【问题标题】:Is it possible to iterate a mongo cursor twice?是否可以两次迭代 mongo 游标?
【发布时间】:2017-09-21 14:46:30
【问题描述】:

换句话说,有没有办法将它倒回到开头?

编辑

我正在使用 mongo shell 和 pymongo。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    Ruby API 具有 rewind! 方法,可以完全满足您的需求。

    Python API 也有 cursor.rewind() 方法。

    PHP API 也有 cursor.rewind() 方法。

    但是,Java 或 C++ API 都没有 rewind 方法。都可以从official API page找到。

    【讨论】:

    • 很高兴知道,但我没有使用 Ruby。
    • 我不知道这两个 API 中的任何一个,但我想知道它们是否都只是驱动技巧 - 这是 MongoDB 原生支持的东西
    • 根据文档和code,数据库本身不支持此功能,并将向服务器发送新查询。
    【解决方案2】:

    pymongo中的游标有.rewind()方法,可以参考sample code from previous question with answer that apply

    然而,本机 mongo shell api 不提供这种方法,请参阅method help() on DBQuery object prototype.

    > db.collection.find().help()
    find() modifiers
            .sort( {...} )
            .limit( n )
            .skip( n )
            .count() - total # of objects matching query, ignores skip,limit
            .size() - total # of objects cursor would return, honors skip,limit
            .explain([verbose])
            .hint(...)
            .showDiskLoc() - adds a $diskLoc field to each returned object
    
    Cursor methods
            .forEach( func )
            .map( func )
            .hasNext()
            .next()
    

    【讨论】:

      【解决方案3】:

      您可以使用cursor.reset();

      对于 PHP:$cursor->reset();

      然后在重置后随时运行您的foreach($cursorData as $data)

      【讨论】:

        猜你喜欢
        • 2016-09-01
        • 1970-01-01
        • 2017-01-20
        • 2019-12-05
        • 2015-07-30
        • 1970-01-01
        • 2012-07-08
        • 2020-05-07
        • 1970-01-01
        相关资源
        最近更新 更多