Open In App

MongoDB Aggregation $group Command

The $group command in MongoDB’s aggregation framework is a powerful tool for performing complex data analysis and summarization. It allows users to group documents based on specified keys and perform aggregate functions on the grouped data. In this article, We will learn about $group command, explaining its concepts and usage with beginner-friendly examples.

Understanding the $group Command

Syntax:



The basic syntax of the $group command is as follows:

{ $group: { _id: <expression>, <field1>: { <accumulator1>: <expression1> }, ... } }

Explanation:



Examples of $group Command

Suppose we have a collection named sales containing documents representing sales transactions. Each document has fields like 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
}
]

Examples 1: $group on Single Key

We want to calculate the total sales amount for each category.

db.sales.aggregate([
{
$group: {
_id: "$category",
totalSales: { $sum: "$amount" }
}
}
])

Output:

[
{
"_id": "Category 1",
"totalSales": 220
},
{
"_id": "Category 2",
"totalSales": 350
}
]

Explanation:

Example 2: $group on Multiple Keys

Let’s use the previous example to calculate for the average and maximum sales amount for each category.

db.sales.aggregate([
{
$group: {
_id: "$category",
totalSales: { $sum: "$amount" },
avgSales: { $avg: "$amount" },
maxSales: { $max: "$amount" }
}
}
])

Output:

[
{
"_id": "Category 1",
"totalSales": 220,
"avgSales": 110,
"maxSales": 120
},
{
"_id": "Category 2",
"totalSales": 350,
"avgSales": 175,
"maxSales": 200
}
]

Explanation: In this example, we’ve added $avg and $max functions to compute the average and maximum sales amounts for each category.

Example 3: Using Expressions

In addition to field names, $group can accept expressions for grouping and aggregation. Expressions can include arithmetic operations, conditional expressions, and more, allowing for flexible data processing.

Suppose we want to categorize sales transactions into two groups: “High” for transactions with amounts greater than $100 and “Low” for transactions with amounts less than or equal to $100. We can achieve this using conditional expressions within the $group command

db.sales.aggregate([
{
$group: {
_id: { $cond: { if: { $gt: ["$amount", 100] }, then: "High", else: "Low" } },
totalSales: { $sum: "$amount" }
}
}
])

Output:

[
{
"_id": "High",
"totalSales": 550
},
{
"_id": "Low",
"totalSales": 120
}
]

Explanation: In this example, we use the $cond operator to create a conditional expression that categorizes transactions based on their amounts.

Conclusion

Overall, The $group command in MongoDB’s aggregation framework is a powerful tool for summarizing and analyzing data. By grouping documents based on specified keys and applying aggregate functions, users can derive valuable insights from their datasets. Whether calculating totals, averages, or performing complex hierarchical grouping, the $group command provides the flexibility and functionality needed for a wide range of data analysis tasks. Experiment with different groupings and aggregate functions to unlock the full potential of MongoDB’s aggregation capabilities and gain information into your data.


Article Tags :