0
0
MongoDBquery~5 mins

$group stage for aggregation in MongoDB

Choose your learning style9 modes available
Introduction

The $group stage helps you collect and combine data by categories, like counting or summing values for each group.

Counting how many orders each customer made.
Summing total sales per product.
Finding the average rating for each movie.
Grouping employees by department to find total salaries.
Syntax
MongoDB
db.collection.aggregate([
  {
    $group: {
      _id: <expression>,
      <field1>: { <accumulator1> : <expression1> },
      <field2>: { <accumulator2> : <expression2> },
      ...
    }
  }
])

The _id field defines the group key (what you group by).

Accumulator operators like $sum, $avg, $max, and $min calculate values for each group.

Examples
Count orders per customer by grouping on customerId and summing 1 for each order.
MongoDB
db.orders.aggregate([
  { $group: { _id: "$customerId", totalOrders: { $sum: 1 } } }
])
Sum sales amounts for each product.
MongoDB
db.sales.aggregate([
  { $group: { _id: "$product", totalSales: { $sum: "$amount" } } }
])
Calculate average rating for each movie genre.
MongoDB
db.movies.aggregate([
  { $group: { _id: "$genre", avgRating: { $avg: "$rating" } } }
])
Sample Program

This query groups orders by customerId and counts how many orders each customer made.

MongoDB
db.orders.aggregate([
  { $group: { _id: "$customerId", totalOrders: { $sum: 1 } } }
])
OutputSuccess
Important Notes

The _id field cannot be omitted; it defines how documents are grouped.

You can group by multiple fields by using an object in _id, like { customerId: "$customerId", status: "$status" }.

Summary

$group collects documents into groups based on a key.

Use accumulator operators to calculate sums, counts, averages, and more.

The _id field defines the grouping key and is required.