Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To paginate the data while sorting it in MongoDB, you can use the skip() and limit() methods along with the sort() method. Here is an example:

Let's say you have a collection named users with the following documents:

{ "_id": 1, "name": "Alice", "age": 30 }
{ "_id": 2, "name": "Bob", "age": 25 }
{ "_id": 3, "name": "Charlie", "age": 35 }
{ "_id": 4, "name": "Dave", "age": 40 }

To paginate the data while sorting it by age in ascending order, you can use the following query:

db.users.find().sort({age: 1}).skip(2).limit(2)

This will skip the first two documents and return the next two documents sorted by age in ascending order:

{ "_id": 1, "name": "Alice", "age": 30 }
{ "_id": 4, "name": "Dave", "age": 40 }

Here, skip(2) skips the first two documents and limit(2) limits the result to two documents. The sort({age: 1}) sorts the documents by age in ascending order.

Note that if you have a large collection, using skip() can be inefficient as it has to scan all the skipped documents. In that case, you can use the $gt operator to specify the last document seen and the limit() method to limit the number of documents returned. For example:

db.users.find({_id: {$gt: last_id}}).sort({age: 1}).limit(2)

Here, last_id is the _id of the last document seen in the previous page. The query returns the next two documents sorted by age in ascending order.