I have the following MongoDB aggregation pipeline:
const doc = await Model.aggregate([
{
$facet: {
metadata: [{ $count: 'totalCount' }],
// data: dataPipeline,
data: [
{ $match: { 'sysData.status': 'pending' } },
{ $sort: parseSort(req.query.sort) },
{ $project: parseFields(req.query.fields) },
{ $skip: (parsePage(req.query.page) - 1) * parseLimit(req.query.limit) },
{ $limit: parseLimit(req.query.limit) },
{
$group: {
_id: null,
data: {
$push: '$$ROOT',
},
filterCount: {
$sum: 1,
},
},
},
],
},
},
]);
I would like to have the total number of documents with “totalCount”, which works correctly. With “filterCount” I would like to have the number of matched documents. Because of the limit stage it will count the number of limited documents which is not correct. How can I resolve this?