为了速度,我想将查询限制为10个结果
db.collection.find( ... ).limit(10)
Run Code Online (Sandbox Code Playgroud)
但是,我也想知道总数,所以说"有124但我只有10".有一个很好的有效方法吗?
joh*_*rab 37
默认情况下,count()
忽略limit()
并计算整个查询中的结果.因此,当您执行此操作时,var a = db.collection.find(...).limit(10);
运行a.count()
将为您提供查询的总计数.
小智 25
执行count(1)包括限制和跳过.
cursor.count()
应该忽略cursor.skip()
并cursor.limit()
默认.
资料来源:http://docs.mongodb.org/manual/reference/method/cursor.count/#cursor.count
@johnnycrab接受的答案是针对mongo CLI.
如果你必须在Node.js和Express.js中编写相同的代码,你必须像这样使用它才能使用"count"函数和toArray的"结果".
var curFind = db.collection('tasks').find({query});
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样运行两个函数(一个嵌套在另一个中)
curFind.count(function (e, count) {
// Use count here
curFind.skip(0).limit(10).toArray(function(err, result) {
// Use result here and count here
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16879 次 |
最近记录: |