0
0
MongoDBquery~5 mins

Pagination pattern with skip and limit in MongoDB

Choose your learning style9 modes available
Introduction

Pagination helps you see data in small parts instead of all at once. It makes browsing big lists easier and faster.

When showing a list of products on a website page by page.
When displaying user comments in chunks instead of all at once.
When loading search results gradually to save time and data.
When you want to let users jump to a specific page of data.
When handling large collections to avoid slow loading.
Syntax
MongoDB
db.collection.find(query).skip(number_to_skip).limit(number_to_show)
Use skip to jump over a number of documents.
Use limit to set how many documents to return.
Examples
Get the first 5 products (page 1).
MongoDB
db.products.find().skip(0).limit(5)
Get the next 5 products (page 2), skipping the first 5.
MongoDB
db.products.find().skip(5).limit(5)
Get 10 active users, skipping the first 10 active users.
MongoDB
db.users.find({active: true}).skip(10).limit(10)
Sample Program

This query shows products on page 3, with 4 products per page. It skips the first 8 products and shows the next 4.

MongoDB
use shopdb

// Show page 3 of products, 4 items per page
const page = 3;
const perPage = 4;
const skipCount = (page - 1) * perPage;
db.products.find().skip(skipCount).limit(perPage).forEach(doc => printjson(doc));
OutputSuccess
Important Notes

Skipping many documents can slow down queries on large collections.

Use indexes to speed up pagination queries.

For very large data, consider other pagination methods like range queries.

Summary

Pagination divides data into pages using skip and limit.

skip jumps over documents, limit sets how many to show.

Good for showing data in small, easy-to-handle parts.