title: MongoDB pagination on arrays - Check if $slice reached the beginning of the array
body: <p>In my application i have an box where users can read comments. If some user scrolls down, it loads more and more comments, everything fine. I slice the array from the back to the begin because i use <code>$push</code> whenever somebody write some comment so i slice it like this <code>$slice: [ -5 , 5]</code>. This will slice the last 5 elements out of the array. The <code>-5</code> is actually an variable in my aggregation pipeline. Whenever i loaded some comments i decrease the value from <code>-5</code> to <code>-10</code> and so on so on. The problem i got here is if my array has an legth for example of 50, and i execute this slice <code>$slice: [ -70, 5]</code> i get the first 5 comments, but i expected to receive 0. The result is that i have an infinity scrollbar witch loads over and over the same 5 first comments. How do i fix this?</p>
  
  <pre><code>let result = await Post.aggregate([
      {
        $match: {
          _id: userId,
          "posts._id": postId
        }
      },
      {
        $addFields: {
          posts: {
            $map: {
              input: "$posts",
              as: "p",
              in: {
                _id: "$$p._id",
                comments: { $slice: ["$$p.comments", -start, 5] }
              }
            }
          }
        }
      },
      {
        $project: {
          posts: {
            $filter: {
              input: "$posts",
              as: "posts",
              cond: { $eq: ["$$posts._id", postId] }
            }
          }
        }
      }
    ]);
  </code></pre>