Paginating the result according to ascending order

Lets say i have 1000 users in user collection in mongoDb. Each user document is like

“name” : “bharath”,
“age” : 24,
“email” : ""

Like this thousand users document i have in user collection MongoDb, Now I want to get only 50 results at a time in one page and that too users should be ordered in ascending order according to their name. So how can i achieve this without using third party pagination methods??

Which library are you using to connect to mongo? Does the mongo query language know about some sorting and limiting keywords?

The mongo library i am using is mongodb

If you are writing your queries directly, you should be able to use the aggregations $sort, $limit and $skip.

At least from a quick skimming of the mongo docs they should be what you are searching for.

From mongo docs using $skip is often expensive because it requires the server to walk from the beginning of the collection. So, i am thinking to achieve this in different manner. Can u suggest is there any best way to achieve this?

In SQL one would do the same and depending on how good the index is, it’s walking the collection there every time.

Another possibility is to store the result in memory related to the session and paginate from there, but probably you will end up with the exact same walking from beginning everytime problem as well.