$sort/$limit/$skip
These stages order, trim and page the documents flowing through a pipeline.
In this page:
Syntax
{ $sort: { field: -1 } }
{ $skip: n }
{ $limit: n }
$sort/$limit/$skip
$sort orders documents, $limit keeps the first n and $skip drops the first n. Sort then limit gives top-N results and MongoDB can optimize that combination.
Put $sort before $limit and $skip for meaningful paging, and ensure a supporting index for large data.
Note:
$sort followed by $limit is optimized into a top-N sort.
Example: $sort/$limit/$skip
test> db.scores.insertMany([{ _id: 1, n: "Ada", s: 70 }, { _id: 2, n: "Bob", s: 90 }, { _id: 3, n: "Cy", s: 85 }, { _id: 4, n: "Di", s: 60 }, { _id: 5, n: "Ed", s: 95 }])
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
}
test> db.scores.aggregate([{ $sort: { s: -1 } }, { $limit: 3 }, { $project: { _id: 0, n: 1, s: 1 } }])
[ { n: 'Ed', s: 95 }, { n: 'Bob', s: 90 }, { n: 'Cy', s: 85 } ]
test> db.scores.aggregate([{ $sort: { s: -1 } }, { $skip: 2 }, { $limit: 2 }, { $project: { _id: 0, n: 1 } }])
[ { n: 'Cy' }, { n: 'Ada' } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using $limit before $sort
- Skipping without a stable sort
- Sorting without an index on big collections
Chapter Summary
- $sort orders
- $limit keeps n
- $skip drops n
- Sort first, then limit or skip
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: