Count in Atlas search pipeline timeouts

Hi everybody,

is there a way to count documents in a reasonable time when using aggregation? How could I build pagination when using text search?

Unfortunately, the current code timeouts when aggregation returns more than 5K results.

My code:

    db.collection("products").aggregate([
      {
        $search: { text: { query: search, path: "name" } },
      },
      { $skip: offset },
      { $limit: limit },
      {
        $facet: {
          stats: [{ $count: "total_found" }],
          documents: [{ $skip: offset }, { $limit: limit }],
        },
      },
    ])
    .toArray();