We use $limit and $skip to control how many results we get and where to start in a list of data. This helps us see just the part we want.
0
0
$limit and $skip stages in MongoDB
Introduction
When you want to show only the first 5 items from a big list of products.
When you want to skip the first 10 messages and see the next ones in a chat app.
When you want to create pages of results, like showing 10 users per page.
When you want to test a small part of your data without loading everything.
When you want to jump to a specific spot in your data list to continue reading.
Syntax
MongoDB
{ $limit: <number> },
{ $skip: <number> }$limit sets the maximum number of documents to return.
$skip tells MongoDB to ignore a number of documents before returning results.
Examples
This will return only the first 3 documents from the collection.
MongoDB
[ { $limit: 3 } ]This will skip the first 5 documents and return the rest.
MongoDB
[ { $skip: 5 } ]This skips the first 2 documents, then returns the next 4 documents.
MongoDB
[ { $skip: 2 }, { $limit: 4 } ]Sample Program
This query skips the first 2 books and then returns the next 3 books from the books collection.
MongoDB
db.books.aggregate([
{ $skip: 2 },
{ $limit: 3 }
])OutputSuccess
Important Notes
Always use $skip before $limit to get the correct slice of data.
Using $skip with a large number can be slow because MongoDB still processes skipped documents.
These stages are often used together to create pagination in apps.
Summary
$limit controls how many results you get back.
$skip tells MongoDB to ignore some results before starting to return data.
Use them together to get specific parts of your data, like pages.