MongoDB - Aggregation Framework (Total Count)

后端 未结 7 1940
余生分开走
余生分开走 2020-12-31 07:42

When running a normal \"find\" query on MongoDB I can get the total result count (regardless of limit) by running \"count\" on the returned cursor. So, even if I limit to re

7条回答
  •  感动是毒
    2020-12-31 08:24

    I got the same problem, and solved with $project, $slice and $$ROOT.

    db.article.aggregate(
    { $group : {
        _id : '$author',
        posts : { $sum : 1 },
        articles: {$push: '$$ROOT'},
    }},
    { $sort : { posts: -1 } },
    { $project: {total: '$posts', articles: {$slice: ['$articles', from, to]}},
    ).toArray(function(err, result){
        var articles = result[0].articles;
        var total = result[0].total;
    });
    

    You need to declare from and to variable.

    https://docs.mongodb.com/manual/reference/operator/aggregation/slice/

提交回复
热议问题