Search code examples
mongodbmongooseazure-cosmosdb-mongoapi

How to achieve pagination in mongoDB without using $facet as AZURE and AWS do not support it


I have collection something like below

[
  {
    _id: id1,
    user: user1,
    city: "test1"
  },
  {
    _id: id2,
    user: user2,
    city: "test1"
  },
  {
    _id: id3,
    user: user3,
    city: "test2"
  },
.....
]

I want get something like, further, I want to sort results based on _id etc.

[
  results: [
    {
      _id: id1,
      user: user1,
      city: "test1"
    },
    {
      _id: id1,
      user: user2,
      city: "test1"
    },
   ...
  ],
  totalResults: 220,
  pageNumber: 2
]

I am using moongoose as well in my project


Solution

  • db.collection.aggregate([
      {
        "$match": {
          query
        }
      },
      {
        $project: {
          user: "$user"
        }
      },
      {
        "$sort": shortBy
      },
      {
        $group: {
          _id: null,
          postCount: {
            $sum: 1
          },
          results: {
            $push: '$$ROOT'
          }
        }
      },
      {
        $project: {
          total: '$postCount',
          results: {
            $slice: [
              '$results',
              skip,
              limit
            ]
          }
        }
      }
    ])