$group

The $group operator in MongoDB is used to aggregate and perform operations on the grouped data. The operator allows you to categorize documents in a collection based on specific fields and perform various operations on each group. These operations range from counting the number of documents in a group, to summing up the values of a particular field, to calculating average values, and many more.

Basic Usage

The basic syntax for the $group operator is as follows:

{
  $group: {
    _id: <expression>,
    <field1>: { <accumulator1> : <expression1> },
    ...
  }
}

Here’s a quick breakdown of the components:

Suppose we have a collection called orders, which contains documents representing sales data.

[
  { _id: 1, customer_id: 'C1', amount: 110 },
  { _id: 2, customer_id: 'C2', amount: 150 },
  { _id: 3, customer_id: 'C1', amount: 90 },
  { _id: 4, customer_id: 'C3', amount: 200 },
  { _id: 5, customer_id: 'C2', amount: 50 },
];

Now, let’s group the data by customer_id and calculate each customer’s total spent amount.

db.orders.aggregate([
  {
    $group: {
      _id: '$customer_id',
      total_spent: { $sum: '$amount' },
    },
  },
]);

This query would result in the following:

[
  { _id: 'C1', total_spent: 200 },
  { _id: 'C2', total_spent: 200 },
  { _id: 'C3', total_spent: 200 },
];

Using the $group operator, documents in the orders collection were grouped by customer_id, and the total spent amount for each customer was calculated using the $sum accumulator.