The `$group` operator in MongoDB is used to group documents by some specified expression and output for each distinct grouping a document that contains the `_id` and the accumulated results for each group.
Here’s an example:
Assume we have a collection named `orders` with documents structured like:
```
[
{ “_id”: 1, “item”: “apple”, “price”: 10, “quantity”: 10 },
{ “_id”: 2, “item”: “banana”, “price”: 20, “quantity”: 15 },
{ “_id”: 3, “item”: “apple”, “price”: 10, “quantity”: 20 },
{ “_id”: 4, “item”: “banana”, “price”: 20, “quantity”: 10 },
]
```
If you want to calculate the total cost for each item(`totalCost = price * quantity`), you can group by `item` and use the `$sum` operator:
```
db.orders.aggregate(
[
{
$group: {
_id: “$item”, // Indicate the field we want to group by
totalCost: { // The new field will contain the result of the following operation
$sum: { $multiply: [ “$price”, “$quantity” ] } // Multiply price with quantity and then sum it
}
}
}
]
)
```
The query above will return:
```
[
{ “_id”: “apple”, “totalCost”: 300 },
{ “_id”: “banana”, “totalCost”: 500 },
]
```
Where `_id` is the value by which documents are grouped.
In this example, we used the `$multiply` and `$sum` operators, but there are many other operators that can be used with `$group` like `$avg`, `$first`, `$last`, `$max`, `$min`, `$push`, `$addToSet`, etc.
The general syntax of the `$group` operator is:
```
{ $group: { _id:
```