Limiting results in MongoDB but still getting the full count?

后端 未结 5 497
不思量自难忘°
不思量自难忘° 2020-12-03 09:38

For speed, I\'d like to limit a query to 10 results

db.collection.find( ... ).limit(10)

However, I\'d also like to know the total count, so

5条回答
  •  醉酒成梦
    2020-12-03 10:28

    The accepted answer by @johnnycrab is for the mongo CLI.

    If you have to write the same code in Node.js and Express.js, you will have to use it like this to be able to use the "count" function along with the toArray's "result".

    var curFind = db.collection('tasks').find({query});
    

    Then you can run two functions after it like this (one nested in the other)

    curFind.count(function (e, count) {
    
    // Use count here
    
        curFind.skip(0).limit(10).toArray(function(err, result) {
    
        // Use result here and count here
    
        });
    
    });
    

提交回复
热议问题