$match is an aggregation pipeline stage that keeps only documents satisfying specified query conditions. Filtering early reduces the documents processed by later stages, while the source collection remains unchanged unless the pipeline includes $merge or $out. section 6.1.1 section 6.1.2
Use $match effectively by applying it before stages that process or reshape data:
- Place $match near the beginning of the pipeline to remove unnecessary documents before grouping, sorting, limiting, or other processing. section 6.1.2
- Combine it with stages such as $group, $sort, and $limit to turn filtered documents into focused summaries or smaller result sets. section 6.1.1
- Treat $match as a filtering step rather than a data-modification operation; aggregation results do not change stored documents by default. section 6.1.1
Filter routes before ranking airports
In db.routes.aggregate(), use { $match: { airplane: "CR2" } } to retain CR2 routes. Then group by $src_airport, count routes with $sum, sort counts descending, and limit the output to five 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 and its sample output, including the $match condition and the stages that consume its filtered documents. section 6.1.1
