$group:
In MongoDB, the $group operator is used in the MongoDB Shell (mongo shell) as part of the aggregation framework.
It allows you to group documents from a collection based on specified criteria and perform various calculations or transformations on the grouped data.
The $group
operator has the following syntax:
{
$group: {
_id: <expression>,
field1: { <accumulator1> : <expression1> },
field2: { <accumulator2> : <expression2> },
...
}
}
Let's break down each component of the $group operator:
$group: This is the stage of the aggregation pipeline where you define the grouping operation.
_id: This field specifies the criteria for grouping the documents. It can be an existing field in the documents or a computed expression. The _id value defines the unique identifier for each group.
field1, field2, etc.: These fields represent the output fields you want to include in the resulting documents. You can use aggregation accumulators to perform calculations or transformations on these fields.
<accumulator1>, <expression1>, <accumulator2>, <expression2>, etc.: These are aggregation accumulators and expressions that define the calculations or transformations you want to perform on the grouped data. Accumulators are special operators that aggregate values from multiple documents within a group.
Some commonly used accumulators in the $group include:
$sum: Calculates the sum of a specified field within a group.
$avg: Computes the average value of a specified field within a group.
$min: Finds the minimum value of a specified field within a group.
$max: Retrieves the maximum value of a specified field within a group.
$push: Collects values of a specified field into an array within a group.
$addToSet: Collects unique values of a specified field into an array within a group.
Here's an example to illustrate the usage of $group
in the MongoDB Shell:
db.sales.aggregate([
{
$group: {
_id: "$product",
totalSales: { $sum: "$quantity" },
averagePrice: { $avg: "$price" }
}
}
])
In this example, we have a collection called "sales" with documents containing fields "product," "quantity," and "price." The $group stage groups the documents by the "product" field and calculates the total sales quantity and average price for each product.
It's important to note that the field names, collection name, and the specific calculations you want to perform will vary based on your data and requirements. The $group operator is a powerful tool for aggregating and summarizing data in MongoDB.
Note:$group the document based on _id filed with unique value.
0 Comments