I'm using mongodb aggregation pipeline to fetch some data. After several stages of filtering in my aggregation, I want to have the count of the document before I move to the stage of pagination (sort, skip & limit). The choice I've had was to use $facet, which helped me to do it:
db.collection.aggregate([
{
...
$matching and filtering documents
...
},
{
$facet: {
data: [
{ $sort: { "price": -1 } },
{ $skip: 0 },
{ $limit: 10 },
],
count: [{ $count: "totalItems" }],
},
},
]);
The issue is that, in the sorting stage, $facet doesn't make use of indexes, and that leads to a big amount of time to perform the operation (large amount of data). I want to learn an efficient way to have an output like: { data: data, count: totalItems }