$sort orders documents within an aggregation pipeline by one or more fields, in ascending or descending order. It supports practical tasks such as ranking grouped results for analysis or presentation while leaving the source collection unchanged unless the pipeline writes through $merge or $out. section 6.1.1 section 6.6
Use $sort effectively by combining it with other pipeline stages:
- Place $match early to reduce the documents that later stages, including sorting, must process. section 6.1.2
- Index fields used for sorting to speed execution and help prevent performance bottlenecks. section 6.1.2
- Apply $limit when only the highest- or lowest-ranked results are needed, reducing memory use and execution time. section 6.1.1 section 6.1.2
Rank airports by route count
After filtering routes for airplane type "CR2" and grouping by source airport, use { $sort: { totalRoutes: -1 } } to rank airports by descending route count. Follow it with { $limit: 5 } to return only the five busiest airports. section 6.1.1
Listing 6.1 Executing an aggregation pipeline
db.routes.aggregate([
{
$match: { airplane: "CR2" } // Filter documents where the
➥airplane is "CR2"
},
{
$group: {
_id: "$src_airport", // Group by source airport
totalRoutes: { $sum: 1 } // Count the number of routes
➥from each source
}
},
{
$sort: { totalRoutes: -1 } // Sort the results by the
➥number of routes in descending order
},
{
$limit: 5 // Limit the number of displayed
➥documents to 5
}
])
[
{ _id: 'DME', totalRoutes: 19 },
{ _id: 'SVX', totalRoutes: 17 },
{ _id: 'OVB', totalRoutes: 12 },
{ _id: 'LED', totalRoutes: 11 },
{ _id: 'OMS', totalRoutes: 8 }
]
Inspect the complete executable pipeline showing $match, $group, $sort, and $limit together with sample output. section 6.1.1
