Stop Using Loops—Use $group in MongoDB for Smarter Data Summaries


Hey devs! 👋
Need to summarize, total, or categorize data in MongoDB? $group
has you covered! 📊
It lets you group documents by fields and apply operations like $sum
, $avg
, or $count
—perfect for reports, dashboards, and analytics. Let’s break it down! 🔍
If you’ve ever used SQL’s GROUP BY
, then MongoDB’s $group
aggregation stage will feel familiar—but with a lot more power packed in. Whether you're building a dashboard, processing data analytics, or just want to summarize records, $group
is your go-to stage in MongoDB’s aggregation framework.
In this article, we’ll break down what $group
does, where and why it’s used, and show you a real-world example with a sample aggregation pipeline. Let’s dive in!
What is $group
in MongoDB? 📘
In simple terms, the $group
stage groups input documents by a specified identifier expression and allows you to perform operations like:
Counting documents in each group
Summing values (like total sales)
Calculating averages, min, max, etc.
Creating arrays of grouped values
It's a powerful tool for summarizing or transforming data, especially when dealing with large datasets.
Where and Why Is $group
Used? 🔍
The $group
stage is widely used in:
Analytics dashboards (e.g., total sales by month)
Reporting tools (e.g., average ratings per product)
ETL pipelines (e.g., data transformations before export)
Inventory systems (e.g., stock count per category)
Finance apps (e.g., expense tracking per category)
Think of any scenario where you need to “group” and perform calculations—$group
is the solution.
Real-World Scenario: E-commerce Order Summary 🌐
Imagine you're building an e-commerce analytics feature. You store each order in a MongoDB collection called orders
. Each document includes:
{
"_id": ObjectId("..."),
"customerId": "CUST1001",
"orderAmount": 150,
"paymentStatus": "Paid",
"orderDate": "2025-04-09T12:30:00Z"
}
Now, let’s say you want to find the total amount spent by each customer. Here's where $group
becomes super handy.
Example Aggregation Pipeline with $group
🛠
db.orders.aggregate([
{
$group: {
_id: "$customerId", // Group by customerId
totalAmountSpent: { $sum: "$orderAmount" }, // Sum all orderAmount values per customer
totalOrders: { $sum: 1 }, // Count number of orders per customer
},
},
]);
Output 🧾:
[
{
"_id": "CUST1001",
"totalAmountSpent": 300,
"totalOrders": 2
},
{
"_id": "CUST1002",
"totalAmountSpent": 450,
"totalOrders": 3
}
]
What’s Happening Here? ✅
_id: "$customerId"
→ This defines the key to group by.$sum: "$orderAmount"
→ This calculates total spending.$sum: 1
→ A neat trick to count documents in each group.
Bonus: Other Useful $group
Operators 🧠
Here are some other powerful operators you can use with $group
:
Operator | Description |
$avg | Calculates the average |
$max | Gets the maximum value |
$min | Gets the minimum value |
$push | Adds values to an array |
$addToSet | Adds unique values to an array |
$first | Returns the first document in group |
$last | Returns the last document in group |
Conclusion 🔚
The $group
stage is a core building block of MongoDB’s aggregation framework. It empowers you to transform raw data into insightful summaries with minimal effort. Whether it’s sales data, user activity, or product metrics, knowing how to use $group
opens up a world of possibilities.
So next time you need to "group and calculate," reach for $group
—MongoDB’s data summarizing superhero. 🦸♂️
Want to Learn More? ✨
Check out MongoDB’s official documentation on
$group
Try building custom reports with aggregation pipelines
Combine
$group
with$match
,$sort
, and$project
for more complex queries
Thank You!
Thank you for reading!
I hope you enjoyed this post. If you did, please share it with your network and stay tuned for more insights on software development. I'd love to connect with you on LinkedIn or have you follow my journey on HashNode for regular updates.
Happy Coding!
Darshit Anjaria
Subscribe to my newsletter
Read articles from Darshit Anjaria directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Darshit Anjaria
Darshit Anjaria
I’m a problem solver at heart, driven by the idea of building solutions that genuinely make a difference in people’s everyday lives. I’m always curious, always learning, and always looking for ways to improve the world around me through thoughtful, impactful work. Beyond building, I love giving back to the community — whether it’s by sharing what I’ve learned through blogs, tutorials, or helpful insights. My goal is simple: to make technology a little more accessible and useful for everyone. Let’s learn, build, and grow together.