Get and count documents in Mongodb

Viewed 35

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 }

1 Answers

In your case specifically, assuming your pipeline qualifies for index usage on the $sort stage, just move it to be before the $facet stage. you are going to sort the entire collection as it is, so there's no benefit of having it within the $facet:

db.collection.aggregate([
  {
    ... 
    $matching and filtering documents 
    ... 
  },
  { $sort: { "price": -1 } },
  {
    $facet: {
      data: [
        { $skip: 0 },
        { $limit: 10 },
      ],
      count: [{ $count: "totalItems" }],
    },
  },
]);
Related