0

I am trying to get some filtered data and it's total count. I want to do both job within single query, so how can I do this. Below is my code.

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) {....});

Now I want to get count with this same query like

{
     $count: "totalcount"
},
Manish Nayak
  • 635
  • 9
  • 18

1 Answers1

0

You can use another aggregate stage called group like this to achieve your goal:

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

your aggregation would be like :

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

also you should use limit and offset as a aggregation stage with $limit and $skip