Pagination in MongoDB using limit and skip methods or $limit and $skip aggregation

Pagination, also known as paging, is the process of dividing a document into discrete pages. To create a pagination system we have two choices: limit and skip methods or using The $limit and $skip from the aggregation framework

Pagination in MongoDB using limit and skip methods

Pagination in MongoDB using limit and skip and aggregate

Preparing data

Imagine that our collection contains the following documents

{ "_id" : ObjectId("5e35a076890d645061ea7db8"), "name" : "article 1" }
{ "_id" : ObjectId("5e35a076890d645061ea7db9"), "name" : "article 2" }
{ "_id" : ObjectId("5e35a076890d645061ea7dba"), "name" : "article 3" }
{ "_id" : ObjectId("5e35a076890d645061ea7dbb"), "name" : "article 4" }

Limit method

The limit method is used to limit the number of returned documents from a cursor. The limit method takes one argument of type number, which is the number of document you want to retrieve from a specific collection.

Example of usage of limit

db.collection.find().limit(2);

Result

{ "_id" : ObjectId("5e35a076890d645061ea7db8"), "name" : "article 1" }
{ "_id" : ObjectId("5e35a076890d645061ea7db9"), "name" : "article 2" }

RDBMS equivalent of limit

select * from articles limit 2;

Skip method

We use Skip method which takes an argument of type number to retrieve only the elements starting from the specified number from a cursor.

Skip usage

db.articles.find().skip(2);

Example of usage of skip

{ "_id" : ObjectId("5e35a076890d645061ea7dba"), "name" : "article 3" }
{ "_id" : ObjectId("5e35bc7d890d645061ea7dbb"), "name" : "article 4" }

The combination of limit and skip is what let us create what we call a pagination system in MongoDB.

Pagination in MongoDB

Consider a case where you want to retrieve the second page where every page contains 2 documents. So in this case we should skip 2 multiply by 1 ("number of documents per page" * "number of page we want to skip") documents and get 2 documents starting from that point.

Pagination in MongoDB

db.articles.find().skip(2).limit(2);

Result

{ "_id" : ObjectId("5e35a076890d645061ea7dba"), "name" : "article 3" }
{ "_id" : ObjectId("5e35bc7d890d645061ea7dbb"), "name" : "article 4" }

RDBMS equivalent of limit

SELECT * FROM articles LIMIT 2 OFFSET 2

Pagination in MongoDB using $limit and $skip aggregate pipeline stages

db.articles.aggregate([
    {$skip: 2},
    {$limit: 2}
])