0
0
MongoDBquery~5 mins

limit method for pagination in MongoDB

Choose your learning style9 modes available
Introduction

The limit method helps you get only a small number of results from a big list. This makes it easier to show data page by page.

When you want to show 10 products per page on an online store.
When you need to display 5 recent messages in a chat app.
When you want to load only 20 user comments at a time on a blog.
When you want to reduce the amount of data sent to the user to save time.
When you want to avoid overwhelming the user with too much information at once.
Syntax
MongoDB
db.collection.find(query).limit(number)

number is how many results you want to get.

You usually use limit with skip to move through pages.

Examples
Get the first 5 products from the products collection.
MongoDB
db.products.find().limit(5)
Get up to 10 messages sent by user Alice.
MongoDB
db.messages.find({user: 'Alice'}).limit(10)
Get the 3 most recent comments by sorting by date descending.
MongoDB
db.comments.find().sort({date: -1}).limit(3)
Sample Program

This query gets the first 3 books from the books collection.

MongoDB
db.books.find().limit(3)
OutputSuccess
Important Notes

If you don't use limit, MongoDB returns all matching documents, which can be slow.

Use limit with skip to get different pages of results.

Always sort your results before paginating to keep order consistent.

Summary

limit controls how many results you get back.

It helps show data in small, easy-to-handle pages.

Use it with skip and sort for full pagination.