This is the function I’m using
MyModel.aggregate([
{ $match: query },
{ $sort: { 'createdAt': -1 } },
{ $skip: skip },
{ $limit: 10 }
], { allowDiskUse : true });
query
is to filter the rows. skip
is dynamic value based on pagination (i.e 0, 10, 20 …). The problem is, the rows for each page in wrong. For instance, I can see a specific row in page 1,2,3,4 at the same time! some rows are missing as well.
Why is it happening?
2
Answers
the dynamic value based on pagination (i.e 0, 10, 20 …) should be used for
limit
, then theskip
should be(page - 1 * limit)
let say,
so your query will skip 0 data and start with the first result up 10th
so if you page query is 2,
so your query will skip 10 data and start with the 11th result up 20th
I think the key to this question is the information that you shared in this comment:
It’s not that the sort doesn’t "work properly" necessarily, it’s that it doesn’t have enough information to sort deterministically each time. The value of
123
doesn’t come before or after another value of123
on its own. As @Noel points out, you need to provide an additional field(s) to your sort.This is also covered here in the documentation:
This is because the
_id
field is unique. If you take that approach it would change your sort to: