MongoDB查询失败

时间:2017-01-23 16:53:23

标签: javascript mongodb

我已将以下查询保存为med.js

var cust = db.Collection.find({"email":null});
var count = 0;
print("total entries: ",cust.length(),"  ",cust.hasNext());
while(cust.hasNext()){
nextCust = cust.next();
db.Collection.update({_id:nextCust._id},{$set : {"email":""}});
count++;
}
print("total updated: ",count);

当我执行此查询时为
mongo dbName --port 13017~ / Documents / med.js

输出是 总条目:491502 false
总更新:0

为什么总条目显示为491502但hasNext()为false。它不会进入while循环

2 个答案:

答案 0 :(得分:3)

cursor.length()函数通过将光标转换为数组来耗尽光标。检查功能代码。

>cur.length
function (){
    return this.toArray().length;
}

因此你得到false

要在不耗尽光标的情况下获取计数,请使用cursor.count()

答案 1 :(得分:3)

您可以在此上下文中使用三种不同的方法。

  • cursor.count()修改光标以返回文档数 在结果集中而不是文档本身。

  • cursor.itcount()计算中的文档总数 游标客户端通过获取和迭代结果集。

  • cursor.size()返回光标后面的文档计数 应用skip()和limit()方法。

cursor.length不是推荐的方法。