title: How can I improve my Mongodb aggregation pipeline, if possible?
body: <p>For one, I'm using MongoDB version 5.0.10 but I believe in the latest there might be a simpler solution using $group and the new accumulators ($firstN) so if you can let me know one that works in my current version and latest please!</p>
  <p>Goal: Paginate through a collection starting from the last page going back to the first. The user of course doesn't know the total amount nor total pages so they for example would give us 0 for the first page, 1 for the second and so on. Using the user inputted page we can calculate the current page after determining some numbers such as the total count and total pages.</p>
  <p>The last page should only return the last items of course while every other page should return the amount in limit.</p>
  <pre><code>[
          { $match: { userId, gameKind } },
          { $sort: { createdAt: -1 } },
          {
            $facet: {
              metadata: [
                { $count: &quot;totalCount&quot; },
                {
                  $addFields: {
                    totalPages: { $floor: { $divide: [&quot;$totalCount&quot;, limit] } },
                  },
                },
                {
                  $addFields: {
                    currentPage: { $subtract: [&quot;$totalPages&quot;, page] },
                  },
                },
                {
                  $addFields: {
                    currentCount: {
                      $cond: {
                        if: {
                          $eq: [&quot;$currentPage&quot;, &quot;$totalPages&quot;],
                        },
                        then: {
                          $mod: [&quot;$totalCount&quot;, limit],
                        },
                        else: limit,
                      },
                    },
                  },
                },
              ],
              data: [{ $skip: page * limit }, { $limit: limit }],
            },
          },
          { $unwind: &quot;$metadata&quot; },
          {
            $set: {
              data: {
                $slice: [&quot;$data&quot;, 0, &quot;$metadata.currentCount&quot;],
              },
            },
          },
        ]
  </code></pre>