← Back to MongoDB Course | Chapter 7: Aggregation | Lesson 5 of 7

$sort/$limit/$skip

These stages order, trim and page the documents flowing through a pipeline.

In this page:

  1. $sort/$limit/$skip
Syntax
javascript
{ $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

bash
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
  1. Using $limit before $sort
  2. Skipping without a stable sort
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.