DBCursor hasNext()处理的记录多于DBCollection实际拥有的记录......为什么?

Bob*_*har 3 mongodb

我有一个使用了蒙戈Java驱动程序蒙戈的Java驱动程序 - 2.8.0.jar参观那里的所有记录在一个单一的集合更新任何不符合预期结构的Groovy脚本.这个脚本的作用就像一个冠军,但是我为什么要处理比集合实际拥有的记录更多的记录.或者,更准确地说,dbCursore.hasNext()迭代的记录多于集合实际拥有的记录.仅当脚本找到要更新的内容时才会出现这种情况.如果脚本在没有更新的情况下执行,则处理的总数是正确的.

hasNext()是否"重新开始"或者记录是否在迭代中移动(如果它们已被更新)?

这是代码......

static def doIt( mongo, normalizer, isDryRun ) {
    def ttlProcessed = 0
    def ttlCandidates = 0
    def ttlUpdated = 0
    def lapCount = 0;
    def lapStartTime = System.currentTimeMillis();

    def db = mongo.getDB( "devices" )
    DBCollection dbCollection = db.getCollection( "profiles" )
    DBCursor dbCursor = dbCollection.find();
    while ( dbCursor.hasNext() ) {
        DBObject source = dbCursor.next();
        DBObject normalized = normalizer.normalize( source )
        // Only update if changed...
        if ( ! ( source.equals( normalized ) ) ) {
            ttlCandidates++
            if ( !isDryRun ) {
                BasicDBObject searchQuery = new BasicDBObject( "_id", normalized.get( "_id" ) )
                WriteResult result = dbCollection.update( searchQuery, normalized, false, false, WriteConcern.SAFE );
                ttlUpdated++
            }
        }
        ttlProcessed++;
        if ( ttlProcessed % 10000 == 0 ) {
            printErr "split: ${lapCount}, splitElapsed: ${calcElapsed( lapStartTime) } ms, elapsed: ${calcElapsed( startTime )} ms, processed: ${ttlProcessed}, candidates: ${ttlCandidates}, updated: ${ttlUpdated}"
            lapCount++
            lapStartTime = System.currentTimeMillis()
        }
    }
    printErr "split: ${lapCount}, splitElapsed: ${calcElapsed( lapStartTime) } ms, elapsed: ${calcElapsed( startTime )} ms, processed: ${ttlProcessed}, candidates: ${ttlCandidates}, updated: ${ttlUpdated}"
}
Run Code Online (Sandbox Code Playgroud)

如果运行更新任何记录,ttlProcessed如何获得的值高于正在处理的集合的数量?

Ada*_*ord 5

这可能发生,因为更新导致文档移动(通常是因为增长).如果文档确实增长并再次处理,它将被视为迭代,但假设您的更新是幂等的(我还没有测试过),那么它就不会成为问题.

如果需要考虑,您可以使用该$snapshot 选项来解决此问题.我还建议阅读这个:

http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database

这些问题本质上是为什么像mongodump和mongoexport这样的工具会走_id索引(即$snapshot默认使用).

如果您想首先考虑阻止移动,请在Padding Factor页面上查看此部分:

http://www.mongodb.org/display/DOCS/Padding+Factor#PaddingFactor-ManualPadding

在运行compact命令时,2.2中还有选项可以设置填充:

http://docs.mongodb.org/manual/release-notes/2.2/#padding-specifiable-on-compact-command