In MongoDB, the group() method is used to group the documents in a collection by a specified field(s) and perform some aggregation functions on the grouped data.
The syntax for the group() method is as follows:
db.collection.group(
{
key: <grouping_field>,
reduce: <aggregation_function>,
initial: <initial_value>
}
)
Here,
collectionis the name of the collection to be grouped.keyspecifies the field(s) by which the documents should be grouped. This can be a single field or multiple fields separated by commas.reducespecifies the aggregation function to be performed on the grouped data. This function must be written in JavaScript and takes two arguments -key(the grouping key) andvalues(an array of values corresponding to the grouping key).initialspecifies the initial value that is passed as an argument to the reduce function.
For example, let’s say we have a collection orders with the following documents:
{
"_id": 1,
"product": "apple",
"quantity": 2,
"price": 1.99
},
{
"_id": 2,
"product": "banana",
"quantity": 3,
"price": 0.99
},
{
"_id": 3,
"product": "orange",
"quantity": 5,
"price": 1.49
},
{
"_id": 4,
"product": "apple",
"quantity": 4,
"price": 1.99
}
We can use the group() method to group the documents by the product field and calculate the total revenue generated by each product using the following command:
db.orders.group(
{
key: { product: 1 },
reduce: function(obj, prev) { prev.total += obj.quantity * obj.price; },
initial: { total: 0 }
}
)
This will return the following output:
[
{
"product": "apple",
"total": 15.96
},
{
"product": "banana",
"total": 2.97
},
{
"product": "orange",
"total": 7.45
}
]
Here, the documents have been grouped by the product field and the total revenue generated by each product has been calculated using the reduce() function. The initial value for the total revenue calculation is 0.




