I am Hack Sparrow
Captain of the Internets.

MongoDB Pagination – using skip()

How to implement pagination in MongoDB using skip()

Curious how pagination might be implemented in MongoDB?

Let's have a data set to play around with so that we can learn by examples. Create a collection named companies and add some documents on it.


The traditional approach to pagination requires the use of skip() and limit() MongoDB cursor functions.

Familiarize yourself with skip() using these example commands:


Understand how limit() works using these commands:


See how skip() and limit() can be coupled to get interesting results. Especially note the last two commands.


By now you probably realize how we might implement pagination in MongoDB. Here is an example code:

db.companies.find().skip(NUMBER_OF_ITEMS * (PAGE_NUMBER - 1)).limit(NUMBER_OF_ITEMS )

NUMBER_OF_ITEMS is the number of items to be shown on a page
PAGE_NUMBER is the current page number

Use db.companies.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.


  1. Very straightforward and logical
  2. Will not scale
  3. Best used for small sized collections

There are two more methods of MongoDB pagination which overcome the problem faced by the skip() method. I'll post them in the next articles. Stay tuned.

5 Responses to “MongoDB Pagination – using skip()”

  1. Cong Luong says:

    Good tutorial, thanks man!

    Can you write a tutorial about paging use mongoose and nodejs?

  2. Captain says:

    Hi Cong, I hope to write one, but can’t really say when.

  3. mjankowski says:

    If it doesn’t scale – why bother? Are you trying to raise a bunch of hacker-wannabes who can’t code proper way?

  4. Captain says:

    I do it for the GK. I don’t provide solutions, I teach concepts. Use it any way you want, whenever and wherever applicable.

  5. Diwakar says:

    How to apply on group by query in mongodb . unable to fetch more 20K data. I want pagination.
    I am not using find() function , i am using group(). i want 20 data per page.

    collection.group(key, cond, initial, reduce);

Make a Comment