In MongoDB, you can group documents by one or more fields using the $group aggregation pipeline stage. To group by multiple fields, you can pass an object as the _id field of the $group stage, where each key in the object corresponds to a field to group by.
Here’s an example query that groups documents in the orders collection by both customer_id and product_id fields, and then calculates the total quantity and revenue for each group:
db.orders.aggregate([
{
$group: {
_id: {
customer_id: "$customer_id",
product_id: "$product_id"
},
total_quantity: { $sum: "$quantity" },
total_revenue: { $sum: { $multiply: ["$quantity", "$price"] } }
}
}
])
In this query, the $group stage uses an object with two keys, customer_id and product_id, to group documents by both fields. The $sum operator is used to calculate the total quantity for each group, and the $multiply operator is used to calculate the total revenue by multiplying the quantity and price fields.
Note that when grouping by multiple fields, the order of the fields in the _id object matters. In the example above, grouping by customer_id first and then by product_id would result in different groups and aggregation results.
