Cursor based pagination in MongoDB with sorting on 2 properties

Viewed 388

My end goal is to implement cursor based pagination in MongoDB, while sorting on 2 properties.

Suppose we have the following collection:

+--------------------------------------+------+-------+
|                 _id                  | cost |  vip  |
+--------------------------------------+------+-------+
| ObjectId("5dae005e665fc34b03c70f8a") |  700 | true  | <-- first query
| ObjectId("5dae005e665fc34b03c70f8c") |   50 | true  | <-- first query
| ObjectId("5dae005e665fc34b03c70f88") |    1 | true  | <-- second query
| ObjectId("5dae005e665fc34b03c70f8b") | 1200 | false | <-- second query
| ObjectId("5dae005e665fc34b03c70f87") |  400 | false |
| ObjectId("5dae005e665fc34b03c70f89") |  300 | false |
+--------------------------------------+------+-------+

And we want the result sorted: {vip: -1, cost: -1}, with a limit of 2. The first query would return row 1 & 2, with the end-cursor being (ObjectId("5dae005e665fc34b03c70f8c")).

With this info, how do I fetch the next 2 rows (i.e. row 3 + 4)?

I have tried with the following filter, but to no help.

{_id: {$lt: ObjectId('5dae005e665fc34b03c70f8c')}, cost: {$gt: 1}}

Thanks for your help.

1 Answers

You can use skip method

db.getCollection('collection').find({}).sort({vip: -1, cost: -1}).skip(2).limit(2)
Related