When it comes to pagination, the first solution that comes to our mind is fetching all the documents form MongoDB and then create a Javascript function to run on that data to do pagination. But there is a better way, you can use limit, sort and skip mongo function to not only do pagination with just one line but also increase performance of your server. Before we get into pagination, let’s start by learning how these functions operate and what are they used for.
limit()
The limit method in mongoDB is used to limit the no of documents that a mongo query fetches from mongo database. This function accepts an integer which is the number of documents you want your query to fetch in single run. Let’s look at a simple mongo query in mongo shell
> use tutorial
> db.pagination.find().limit(10)
The above query will only fetch 10 documents from pagination collection inside tutorial database.
sort()
The sort method in mongoDB is used to sort the documents in ascending or descending order. It accepts an object with key and numeric value. The key is the key in the schema according to which you want to sort the collection and numeric value can either be 1 or -1 for ascending and descending sorting respectively.
> use tutorial
> db.pagination.find().sort({"name": 1})
The above query will sort the result in ascending order according to name key.
skip()
The skip method in MongoDB is used to skip a set number of collections from starting in the mongoose query. skip method accepts a numeric value which is the number of documents to skip.
> use tutorial
> db.pagination.find().skip(10)
The above query will skip first 10 documents from the query result.
Pagination Query
You might have figured it out by understanding these three methods how you can paginate. But if you got stuck here is little pagination query for you.
db.pagination.find().sort("name": 1).skip(10*(page-1)).limit(10)
The above query will give you 10 items in a page and the page will be passed in the body. If the page is 1 it will skip 0 items. If the page is 2 it will skip 10 items and if the page is 200 it will skip 1990 items. If you have any doubts comment below.
[…] to filter. But that’s not the ideal way to do this. MongoDB gifted us with a really powerful operator that can help us make a mongo query for the same. Benefits of using the operator include less code, […]