Here is an example with Pagination, match and sort in mongoose aggregate
const [response] = await Prescribers.aggregate([
{ $match: searchObj },
{ $sort: sortObj },
{
$facet: {
response: [{ $skip: count * page }, { $limit: count }],
pagination: [
{
$count: 'totalDocs',
},
{
$addFields: {
page: page + 1,
totalPages: {
$floor: {
$divide: ['$totalDocs', count],
},
},
},
},
],
},
},
]);
Here count is the limit of each page and page is the the page number. Prescribers is the model
This would return the records similar to this
"data": {
"response": [
{
"_id": "6349308c90e58c6820bbc682",
"foo": "bar"
}
{
"_id": "6349308c90e58c6820bbc682",
"foo": "bar"
},
{
"_id": "6349308c90e58c6820bbc682",
"foo": "bar"
}
{
"_id": "6349308c90e58c6820bbc682",
"foo": "bar"
},
{
"_id": "6349308c90e58c6820bbc682",
"foo": "bar"
},
{
"_id": "6349308c90e58c6820bbc682",
"foo": "bar"
}
{
"_id": "6349308c90e58c6820bbc682",
"foo": "bar"
},
{
"_id": "6349308c90e58c6820bbc682",
"foo": "bar"
}
{
"_id": "6349308c90e58c6820bbc682",
"foo": "bar"
},
{
"_id": "6349308c90e58c6820bbc682",
"foo": "bar"
},
],
"pagination": [
{
"totalDocs": 592438,
"page": 1,
"totalPages": 59243
}
]
}