Chapter Introduction
This chapter describes the pagination query of MongoDB, similar to the usage of pagination in MYSQL. MongoDB's pagination query is implemented through the .limit
and .skip
functions of the Cursor.
Test Data
Insert a few pieces of data into the inventory collection
db.inventory.insertMany( [
{ item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] },
{ item: "notebook", status: "A", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] },
{ item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] },
{ item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" }, instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
Limiting the Returned Data
db.inventory.find({}).limit(5)
Explanation:
- Use the
limit
function to set the maximum number of returned data.
Pagination
db.inventory.find({}).limit(5).skip(2)
Explanation:
- By setting
skip
to skip a certain amount of data andlimit
to limit the number of returned data. -
limit
is similar to thelimit
in SQL, andskip
is similar to the offset in SQL.