Grouping Documents with $group

MongoDB $group – Summarizing Data

How to sum, count, and average data in MongoDB

By Sharanmeet Singh
Tags:MongoDBAggregation$group

MongoDB Query Generator

Generate MongoDB queries and aggregation pipelines

Try Generator

MongoDB $group

The $group stage in MongoDB is similar to SQL’s GROUP BY.


Example

{
  "$group": {
    "_id": "$category",
    "totalSales": { "$sum": "$amount" },
    "avgSale": { "$avg": "$amount" }
  }
}

This groups by category and calculates total + average sales.


Common Operators

  • $sum → Adds numbers
  • $avg → Calculates average
  • $max / $min → Finds extremes
  • $push → Creates an array

Always pair $group with $sort for cleaner results.