【问题标题】:how to use $count and $project together in node js mongoose aggregate如何在节点 js mongoose 聚合中一起使用 $count 和 $project
【发布时间】:2020-04-13 13:43:22
【问题描述】:

我正在尝试获取一些过滤后的数据以及它的总数。我想在单个查询中完成这两项工作,所以我该怎么做。下面是我的代码。

var SubId = 1;
var TypeId = 1;
var lookup = {
      $lookup:
      {
         from: 'sub_types',
         localField: 'sub_id',
         foreignField: 'sub_id',
         as: 'sub_category'
      }
   };

var unwind = { $unwind: "$sub_category" };

var project = {
      "ques_id": 1,
      "ques_txt": 1,
      "ans_txt": 1,
      "ielts_sub_id": 1,
      "ielts_tags_id": 1,
   };

var match = {
      "sub_category.type_id": parseInt(TypeId),
      "sub_category.sub_id": parseInt(SubId),
      "status": 1
   };
ieltsmongoose.collection('ques').aggregate([
  lookup, unwind,
  {
     $match: match
  },
  {
     $project: project
  }
]).limit(max_row).toArray(async function (error, Ques) {....});

现在我想用同样的查询来计数,比如

{
     $count: "totalcount"
},

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

您可以像这样使用另一个名为groupaggregate 阶段来实现您的目标:

{ "$group": { 
        "_id": null, 
        "count": { "$sum": 1}, 
        "data": { "$push": "$$ROOT"  }
}}

你的聚合会是这样的:

ieltsmongoose.collection('ques').aggregate([
  lookup, unwind,
  {
     $match: match
  },
  {
     $project: project
  },
  { "$group": { 
        "_id": null, 
        "count": { "$sum": 1}, 
        "data": { "$push": "$$ROOT"  }
    }
  }
])

你也应该使用limit和offset作为$limit$skip的聚合阶段

【讨论】:

    猜你喜欢
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    相关资源
    最近更新 更多