$sort, $limit, and $skip in the Pipeline
Learners will order and paginate aggregation results and understand the optimizer rules for pushing $match and $sort before $group.
Overview: Ordering and Paginating Results
Three aggregation pipeline stages control the order and volume of results: $sort orders documents by one or more fields, $limit takes only the first N documents, and $skip discards the first N documents. Together they implement sorting and pagination. Understanding where to place them in the pipeline has a major impact on performance.
The $sort Stage
The $sort stage orders documents by the values of one or more fields. Use 1 for ascending and -1 for descending. When multiple fields are specified, documents are sorted by the first field first, then by the second field among ties, and so on—exactly like multi-key sorting in SQL or MongoDB's find().sort().
// Sort by revenue descending, then alphabetically by name for ties
db.products.aggregate([
{ $group: { _id: '$category', revenue: { $sum: '$price' } } },
{ $sort: { revenue: -1, _id: 1 } } // revenue desc, category name asc
]);All lessons in this course
- Pipeline Concepts: Stages, Operators, and Expressions
- $match and $project: Filter and Reshape
- $group: Aggregating and Computing Totals
- $sort, $limit, and $skip in the Pipeline