MongoDB Pagination using skip() and limit()

How to implement pagination with MongoDB??

Let’s for example I have collection named ‘persons’ and add some documents on it.

db.persons.insert({fname:'John', lname: 'Paton'});
db.persons.insert({fname:'Bob', lname: 'Warner'});
db.persons.insert({fname:'Pankaj', lname: 'Gupta'});
db.persons.insert({fname:'Atul', lname: 'Mishra'});

The traditional approach to pagination requires use of  skip() and limit() MongoDB cursor functions. Let’s have a look how we can use these cursor functions to achieve pagination.

db.persons.find().skip(ITEMS_PER_PAGE * (PAGE_NUMBER - 1)).limit(ITEMS_PER_PAGE);

ITEMS_PER_PAGE” – Represents number of items per page.

PAGE_NUMBER” – Represents current page number.

Use db.persons.count() to get the number of documents in the collection and implement the pagination navigation links.

This pagination technique works as you expect and is excellent in every way – as long as you have a small set of data. If you have a collection with hundreds of thousands of documents, this method of pagination will fail – it will become slower with every increasing page. That’s because the cursor has to start from the beginning of the collection to the skip position for every request, and with increasing page number the skip position becomes farther and farther.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s