$group

The `$group` aggregation stage groups documents by specified identifier expressions and applies accumulator expressions to create computed fields for each group. This stage is essential for data aggregation and summarization operations.

Syntax

{
  $group: {
    _id: <expression>,
    <field1>: { <accumulator1>: <expression1> },
    <field2>: { <accumulator2>: <expression2> }
  }
}

Parameters

_idobjectrequired

Required. The expression to group by. Use null to calculate accumulated values for all input documents.

fieldobject

Optional. Computed using accumulator operators like $sum, $avg, $max, $min, $count, etc.

Examples

Sample Data

{
  "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
  "name": "First Up Consultants | Bed and Bath Center",
  "city": "South Amir",
  "staff": {
    "totalStaff": {
      "fullTime": 18,
      "partTime": 17
    }
  },
  "sales": {
    "totalSales": 37701
  }
}

Group staffing analysis by city

Group stores by city and analyze the staffing patterns across different locations.

This query aggregates staff counts and calculates averages per city.

Query:

db.stores.aggregate([
  {
    $group: {
      _id: "$city",
      totalFullTimeStaff: { $sum: "$staff.employeeCount.fullTime" },
      totalPartTimeStaff: { $sum: "$staff.employeeCount.partTime" },
      avgFullTimeStaff: { $avg: "$staff.employeeCount.fullTime" },
      storesInCity: { $count: {} }
    }
  },
  {
    $project: {
      city: "$_id",
      totalFullTimeStaff: 1,
      totalPartTimeStaff: 1,
      avgFullTimeStaff: { $round: ["$avgFullTimeStaff", 1] },
      storesInCity: 1
    }
  },
  { $limit: 2 }
])

Output:

[
  {
    "_id": "New Ellsworth",
    "totalFullTimeStaff": 11,
    "totalPartTimeStaff": 1,
    "avgFullTimeStaff": 11,
    "storesInCity": 1,
    "city": "New Ellsworth"
  }
]

Related