为什么我的 Meteor 应用程序的大于 ($gt) 计数与 mongdb shell 的计数不同?



下面是我在mongodb shell中的输入和输出:

meteor:PRIMARY> db.users.count({"profile.score": {$gt: 50}})
2
下面是我的代码:
var allUsers = Meteor.users.find();
var newCurrentRank = allUsers.count({"profile.score": {$gt: 50}});
console.log("newCurrentRank", newCurrentRank);

这是我的控制台:

I20161004-11:43:42.910(0)? newCurrentRank 12

这是因为Meteor中的 count() 方法返回与查询匹配的游标的文档数。就其本身而言,将查询作为参数传递不会影响计数。因此,在上面的示例中,尽管将查询对象作为参数传递,它仍返回所有12个文档,计数基于 find() 游标,该游标返回集合中的所有文档,因为它被调用时没有任何查询。

您需要的是调用 find() 游标与查询对象,然后调用 count() 方法:

var newCurrentRank = Meteor.users.find({ "profile.score": { "$gt": 50 } }).count();
console.log("newCurrentRank", newCurrentRank);

最新更新