![]() |
VOOZH | about |
The $group Stage in MongoDB aggregation groups documents by a specified field and applies accumulator operators (like $sum, $avg, $max) to compute aggregated values for each group.
Syntax:
{
$group: {
_id: <expression>,
<field1>: { <accumulator1>: <expression1> },
<field2>: { <accumulator2>: <expression2> }
}
}
The $group stage aggregates and analyzes transaction data in MongoDB by summarizing values like counts and totals. To illustrate, consider a sales collection with fields such as product, category, and amount.
[
{
"product": "Product A",
"category": "Category 1",
"amount": 100
},
{
"product": "Product B",
"category": "Category 2",
"amount": 150
},
{
"product": "Product C",
"category": "Category 1",
"amount": 120
},
{
"product": "Product D",
"category": "Category 2",
"amount": 200
}
]
This query calculates the total number of documents present in the sales collection, providing a quick way to determine the dataset size.
db.sales.aggregate([
{
$group: {
_id: null,
count: { $sum: 1 }
}
}
])
Output:
[
{
"_id": null,
"count": 4
}
]
This query retrieves unique category values from the sales collection, helping identify different product categories available in the dataset.
db.sales.aggregate([
{
$group: {
_id: "$category"
}
}
])
Output:
[
{ "_id": "Category 1" },
{ "_id": "Category 2" }
]
This query groups documents by category and calculates the total sales amount for each category in the sales collection
db.sales.aggregate([
{
$group: {
_id: "$category",
totalAmount: { $sum: "$amount" }
}
}
])
Output:
[
{ "_id": "Category 1", "totalAmount": 220 },
{ "_id": "Category 2", "totalAmount": 350 }
]
This query groups documents by category and calculates the total count of documents, sum of sales amount, and average sales amount per category in the sales collection.
db.sales.aggregate([
{
$group: {
_id: "$category",
count: { $sum: 1 },
totalAmount: { $sum: "$amount" },
averageAmount: { $avg: "$amount" }
}
}
])
Output:
[
{
"_id": "Category 1",
"count": 2,
"totalAmount": 220,
"averageAmount": 110
},
{
"_id": "Category 2",
"count": 2,
"totalAmount": 350,
"averageAmount": 175
}
]
This query calculates the total sum of the amount field across all documents in the sales collection, without grouping by any specific field.
db.sales.aggregate([
{
$group: {
_id: null,
totalAmount: { $sum: "$amount" }
}
}
])
Output:
[
{ "_id": null, "totalAmount": 570 }
]