Filter, Sort and Paginate in mongoose returns duplicate value

Viewed 1314

I have a product document in mongodb. I am retrieving data with paging using skip and limit after filtering and sorting, like this using mongoose -

Product.find({gender:'male'})
  .sort(price: 1)
  .skip(page * 25).limit(25);

When page value is 0 it returns the result as expected, but when the page value changes to 1 it returns some results that were already retrieved when page value was 0. I am passing all these parameters through query in nodjs express. How can i retrieve unique value only with sorting and filtering while using pagination with mongoose ?

1 Answers

As mentioned here:

MongoDB does not store documents in a collection in a particular order. When sorting on a field which contains duplicate values, documents containing those values may be returned in any order.

If consistent sort order is desired, include at least one field in your sort that contains unique values. The easiest way to guarantee this is to include the _id field in your sort query.

So you can solve the problem by:

Product.find({gender:'male'})
  .sort({price: 1, _id: 1})
  .skip(page * 25).limit(25);
Related