11

我想在我的收藏中创建一个分页功能。如何在单个查询中找到具有“开始”和“限制”位置的文档并获得总文档数?

4

5 回答 5

19

您不能在一个查询中同时获得两个结果;您能做的最好的事情是使用一个 MongooseQuery对象来获取它们:

var query = MyModel.find({});
query.count(function(err, count) {...});
query.skip(5).limit(10).exec('find', function(err, items) {...});

如果需要,请使用流控制框架,如async干净地并行执行它们。

于 2012-09-22T13:27:12.533 回答
9

您可以使用插件猫鼬分页

$ npm install mongoose-paginate

在您的路线或控制器之后,只需添加:

Model.paginate({}, { page: 3, limit: 10 }, function(err, result) {
    // result.docs 
    // result.total 
    // result.limit - 10 
    // result.page - 3 
    // result.pages 
});
于 2016-03-12T18:35:39.470 回答
4

如果您计划有很多页面,则不应使用跳过/限制,而应计算范围。

请参阅 Scott 对类似问题的回答:MongoDB - paging

于 2012-09-22T13:59:13.800 回答
1

更新 :

使用跳过和限制不利于分页。这是关于它的讨论。

@Wes Freeman,给了一个很好的答案。我阅读了链接的姿势,您应该使用范围查询。n = 0; 我=n+10;db.students.find({ "id" : { $gt: n, $lt: (n+i)} } );

旧答案(不要使用这个)

使用类似的东西

n = db.students.find().skip(n).limit(10);
//pass n dynamically, so for page 1 it should be 0 , page 2 it should be 10 etc

更多文档位于http://www.mongodb.org/display/DOCS/Advanced+Queries

于 2012-09-22T09:54:18.103 回答
0
   user.find({_id:{$nin:friends_id},_id:{$ne:userId}},function(err,user_details){
    if (err)
    res.send(err);
    response ={
        statusCode:200,
        status:true,
        values:user_details
    }
    res.json(response);
   }).skip(10).limit(1);
于 2017-10-24T06:20:03.827 回答