const search = await searchAgent.aggregate([
{$match: {id: Number(fid), status: {$regex: status, $options: 'i'}}},
{$sort: {[order_by]: order == 'desc' ? -1 : 1}},
{$skip: skip},
{$limit: pagelimit},
])
Here I need to get the total number of documents matching the query. As I am using the limit I can’t get the total count of documents.
2
Answers
Here I got the result by using the facet method inside the query. I had given the sort and limit inside the facet method, and given the total count outside the facet. So the limit won't affect getting the total count of documents.
The common approach to solve this is to use the $facet stage, then one pipeline is used to match with the proper
skip
andlimit
and one pipeline for the count.like so:
Mongo Playground