Hi @Nisarg_Bhatt2 ,
To implement pagination you can use a single aggregation pipeline instead of hitting two calls (Data & Count).
Here are the best practices for implementing pagination as follows:
// Method 1: using $setWindowFields
[
// {write your logic here},
{
$setWindowFields: {
sortBy: {
sortField: -1 // to ensure the data is in the correct order
},
output: {
docCount: {
$count: {}
}
}
}
},
{
$skip: 0
},
{
$limit: 10
}
]
it will add the total count in each document in the query output.
// Method 2 : using $facet
[
// {write your logic here},
{
$facet: {
documents: [
{
$sort: {
sortField: -1 // to ensure the data is in the correct order
}
},
{
$skip: 0
},
{
$limit: 10
}
],
docCount: [
{
$count: "count"
}
]
}
},
{
$set:
{
docCount: {
$first: "$docCount.count"
}
}
}
]
It will give a count and data in a single document.
With the above aggregations can fulfill your requirement and hit only one time to the database instead of two calls.
I hope this helps!