$group is an aggregation pipeline stage that groups documents by an expression and computes aggregate values for each group. It emits one result document per distinct group, with the grouping expression stored in _id. section 6.1.1 section 6.1.2
Build a useful grouping pipeline by combining $group with surrounding stages:
- Place $match before $group to reduce the documents that require aggregation. section 6.1.1 section 6.1.2
- Set _id to the grouping expression, such as "$src_airport", and use accumulators such as $sum, $avg, $min, or $max. section 6.1.1 section 6.6
- Follow the grouped results with stages such as $sort or $limit to order or restrict the returned groups. section 6.1.1
Count routes by source airport
A pipeline can filter routes for airplane type CR2, group them by source airport, count each group with { $sum: 1 }, sort by totalRoutes descending, and return the five busiest airports. The grouped output contains fields such as { _id: "DME", totalRoutes: 19 }. 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 representative grouped output. section 6.1.1
let g = {
$group: {
_id: "$group_id",
max_temp: {
$avg: "$obs.temp"
},
avg_watts: {
$avg: "$obs.watts"
},
median_watts: {
$min: "$obs.watts"
},
max_watts: {
$max: "$obs.watts"
},
min_watts: {
$min: "$obs.watts"
}
}
}
Compare ordinary aggregation with streaming grouping, where grouped values are calculated inside a bounded tumbling window. section 15.6.6
