How to count filtered results in $match in mongodb?

Viewed 28

I have an aggregation query like this

nSkip=4, count=25, sortOn='first_name' , order=-1, toMatch='biker' // all variables are dynamic
query={status: true, roles: { $regex: toMatchRole, $options: "m" }} // also dynamic

User.aggregate([
      {
        $match: query
      }, 
      // after this I need the total number of documents that matched the criteria, 
      // before sorting or skipping or limiting in "total_count" variable
      {
        $sort: {
          [sortOn]: order
        }
      },
      {
        $skip: nSkip
      },
      {
        $limit: count
      },
      {
        $project: {
         last_name: 1,
         first_name: 1,
         email: 1
        }
      }
    ])

User Collection

{
  _id:60befdcfa4198332b728f9cd",
  status:false,
  roles:["biker"],
  email:"john@textmercato.com",
  last_name:"aggr",
  first_name:"john",
}

I am not sure how to achieve this without disturbing the rest of the stages in aggregation. Can someone please help me out.

1 Answers

You can use $group

{
    "$group": {
      "_id": null,
      "data": { "$push": "$$ROOT" },
      "total_count": { $sum: 1 }
    }
    },
    { $unwind: "$data" },
    {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [ "$$ROOT", "$data" ]
      }
    }
}

and finally Project the total_count

Working Mongo playground

Related