For a big collection of documents, it is faster to execute 2 queries or use aggregations?

For a big collection of documents, it is faster to execute 2 queries (the paginated results and the total count) or it is faster to use aggregations?

Example aggregation query

[
        { $match: conditions },
        { $sort: { createdAt: -1 } },
        {
          $group: {
            _id: null,
            count: { $sum: 1 },
            results: { $push: "$$CURRENT" },
          },
        },
        {
          $project: {
            count: 1,
            results: { $slice: ["$results", 0, 10] },
          },
        },
      ]

I would appreciate it if you could give me an example

One round-trip to the database is always better than 2.

You may have 2 different queries using $facet.

You current aggregation will probably failed by exceeding some limits as you $push all documents of your collection before $slice’ing only 10 of them.

2 Likes

@Thomas_Papamichail_Vaivas, was my post useful? Did it help you achieve what you wanted to do? If so, show you appreciation and mark my post as the solution. This will benefit all readers.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.