Achieve Pagination with MongoDB?


You can achieve pagination with the help of limit() and skip() in MongoDB.

To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.paginationDemo.insertOne({"CustomerName":"Chris","CustomerAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c949de44cf1f7a64fa4df52")
}
> db.paginationDemo.insertOne({"CustomerName":"Robert","CustomerAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c949df14cf1f7a64fa4df53")
}
> db.paginationDemo.insertOne({"CustomerName":"David","CustomerAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c949dfc4cf1f7a64fa4df54")
}
> db.paginationDemo.insertOne({"CustomerName":"Carol","CustomerAge":28});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c949e3e4cf1f7a64fa4df55")
}
> db.paginationDemo.insertOne({"CustomerName":"Bob","CustomerAge":29});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c949e474cf1f7a64fa4df56")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.paginationDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c949de44cf1f7a64fa4df52"),
   "CustomerName" : "Chris",
   "CustomerAge" : 23
}
{
   "_id" : ObjectId("5c949df14cf1f7a64fa4df53"),
   "CustomerName" : "Robert",
   "CustomerAge" : 26
}
{
   "_id" : ObjectId("5c949dfc4cf1f7a64fa4df54"),
   "CustomerName" : "David",
   "CustomerAge" : 24
}
{
   "_id" : ObjectId("5c949e3e4cf1f7a64fa4df55"),
   "CustomerName" : "Carol",
   "CustomerAge" : 28
}
{
   "_id" : ObjectId("5c949e474cf1f7a64fa4df56"),
   "CustomerName" : "Bob",
   "CustomerAge" : 29
}

Here is the query for pagination with MongoDB −

> db.paginationDemo.find().skip(0).limit(3);

The following is the output −

{ "_id" : ObjectId("5c949de44cf1f7a64fa4df52"), "CustomerName" : "Chris", "CustomerAge" : 23 }
{ "_id" : ObjectId("5c949df14cf1f7a64fa4df53"), "CustomerName" : "Robert", "CustomerAge" : 26 }
{ "_id" : ObjectId("5c949dfc4cf1f7a64fa4df54"), "CustomerName" : "David", "CustomerAge" : 24 }

Updated on: 30-Jul-2019

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements