MongoDB - Aggregation Framework (Total Count)

后端 未结 7 1862
余生分开走
余生分开走 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:46

    If you don't want to run two queries in parallel (one to aggregate the #posts for your top authors, and another aggregation to calculate the total posts for all authors) you can just remove $limit on pipeline and on results you can use

    totalCount = results.length;
    results.slice(number of skip,number of skip + number of limit);
    

    ex:

    db.article.aggregate([
        { $group : {
            _id : "$author",
            posts : { $sum : 1 }
        }},
        { $sort : { posts: -1 } }
        //{$skip : yourSkip},    //--remove this
        //{ $limit : yourLimit }, // remove this too
    ]).exec(function(err, results){
      var totalCount = results.length;//--GEt total count here
       results.slice(yourSkip,yourSkip+yourLimit);
    });
    
    0 讨论(0)
提交回复
热议问题