MongoDB Aggregation $group Stage (original) (raw)

Last Updated : 16 Apr, 2026

The groupStageinMongoDBaggregationgroupsdocumentsbyaspecifiedfieldandappliesaccumulatoroperators(likegroup Stage in MongoDB aggregation groups documents by a specified field and applies accumulator operators (like groupStageinMongoDBaggregationgroupsdocumentsbyaspecifiedfieldandappliesaccumulatoroperators(likesum, avg,avg, avg,max) to compute aggregated values for each group.

**Syntax:

{
$group: {
_id: ,
: { : },
: { : }
}
}

Examples of $group Stage in MongoDB

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
}
]

Example 1: Count the Number of Documents in a Collection

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
}
]

Example 2: Retrieve Distinct Values

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" }
]

Example 3: Group by Category and Calculate Total Amount

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:"sum: "sum:"amount" }
}
}
])

**Output:

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

Example 4: Calculate Count, Sum, and Average

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:"sum: "sum:"amount" },
averageAmount: { avg:"avg: "avg:"amount" }
}
}
])

**Output:

[
{
"_id": "Category 1",
"count": 2,
"totalAmount": 220,
"averageAmount": 110
},
{
"_id": "Category 2",
"count": 2,
"totalAmount": 350,
"averageAmount": 175
}
]

Example 5: Group by null

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:"sum: "sum:"amount" }
}
}
])

**Output:

[
{ "_id": null, "totalAmount": 570 }
]