【问题标题】:MongoDB cursor does not return all documentsMongoDB 游标不返回所有文档
【发布时间】:2017-02-04 16:17:56
【问题描述】:

在 RoboMongo (0.9.0-RC09) 中运行以下 mongo 查询会给出正确数量的文档(使用游标计数函数),而迭代所有文档只会返回一小部分文档:

var allDocuments = db.getCollection('mycollection').find({});
print(allDocuments.size());  // prints 170 000 -> correct

var count = 0;
allDocuments.forEach(function(doc) {
    count++;
});
print(count); // 'randomly' prints values between 30 000 and 44 000

我们是否需要专门配置查询以返回所有文档?

【问题讨论】:

    标签: mongodb mongodb-query robo3t


    【解决方案1】:

    问题已解决: 这是 robomongo shellTimeoutSec 配置(默认:15 秒)的问题,导致光标停止返回更多元素。

    这也解释了 30 000 到 44 000 的“随机”计数(取决于网络速度)。 这是robomogo的门票:https://github.com/paralect/robomongo/issues/1106#issuecomment-230258348

    目前的修复/解决方法是在 robomongo.json 中增加 shellTimeoutSec

    Windows
     0.9.x
      C:\Users\<user>\.config\robomongo\0.9\robomongo.json
     0.8.x
      C:\Users\<user>\.config\robomongo\robomongo.json   
    MAC
     0.9.x
      /Users/<user>/.config/robomongo/0.9/robomongo.json
     0.8.x
      /Users/<user>/.config/robomongo/robomongo.json     
    Linux
     0.9.x
      /home/<user>/.config/robomongo/0.9/robomongo.json
     0.8.x
      /home/<user>/.config/robomongo/robomongo.json
    

    【讨论】:

    • 谢谢!当我意识到并非所有更新都已完成但没有诊断/警告时让我发疯 - wtf??
    【解决方案2】:

    我们需要转换成数组。之后只有我们可以做forEach。 下面试试!!!

    var allDocuments = db.getCollection('mycollection').find({}).toArray();
    print(allDocuments.length);  
    var count = 0;
    allDocuments.forEach(function(doc) {
    count++;
    print("IterCount : ",count); 
    });
    print("FinalCount : ",count); 
    

    // 带光标

    db.getCollection('mycollection').find({}).forEach(function(doc){
    count++;
    print("IterCount : ",count);});
    

    【讨论】:

    • forEach 在光标上定义并且应该可以工作,就像docs.mongodb.com/manual/reference/method/cursor.forEach 中的文档一样(我们使用 mongodb 3.2.6)
    • 这个建议会加载内存中的所有数据。不一定是个好主意。
    • 嗨赫普菲斯!一旦操作完成,光标将立即关闭。它会在光标关闭一段时间后起作用,因此您无法获得结果。我将编辑您尝试的答案
    • 在您的代码中,您将光标结果分配给变量。所以一旦您的 mongodb 操作完成,它将过期。
    • 所以在我的回答中尝试第二个,这将使您了解 cusror。在 mongoDb 中,游标将打开以进行操作,并在该操作完成后立即关闭
    猜你喜欢
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2016-04-26
    • 2018-06-13
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多