The ‘$reduce‘ operator in the MongoDB aggregation framework provides a way to apply a custom operation on an array field and returns the final result of the operation. It is useful in situations where we need to traverse an array field, perform some calculations on each element, and return either a single value or a modified array.
The syntax for ‘$reduce‘ is as follows:
{ $reduce: {
input: <array>,
initialValue: <initialValue>,
in: <operation>
}}
where:
- ‘input‘: specifies the array field on which we want to apply the operation.
- ‘initialValue‘: specifies the initial value to be used in the operation.
- ‘in‘: specifies the operation to be performed on each element of the array. It can be any valid aggregation expression.
Here is an example of using ‘$reduce‘:
Suppose we have a collection of documents representing sales of different products:
{
"_id": 1,
"product": "A",
"sales": [10, 20, 30]
},
{
"_id": 2,
"product": "B",
"sales": [5, 15, 25, 35]
},
{
"_id": 3,
"product": "C",
"sales": [40, 50]
}
Let’s say we want to calculate the total number of sales for each product. We can use ‘$reduce‘ to sum up the elements of the ‘sales‘ array for each document using the following pipeline:
db.sales.aggregate([
{
$project: {
_id: 0,
product: 1,
totalSales: {
$reduce: {
input: "$sales",
initialValue: 0,
in: { $add: ["$$value", "$$this"] }
}
}
}
}
])
The ‘$project‘ stage includes two fields in the output: ‘product‘ and ‘totalSales‘. The ‘$reduce‘ operator is used to sum up the elements of the ‘sales‘ array for each document. The ‘$$value‘ variable represents the running total, which is initialized with ‘0‘ (‘$$initialValue‘). The ‘$$this‘ variable represents the current element of the array being processed.
The output of the above aggregation pipeline will be:
{ "product" : "A", "totalSales" : 60 }
{ "product" : "B", "totalSales" : 80 }
{ "product" : "C", "totalSales" : 90 }
As we can see, ‘$reduce‘ is a powerful operator that allows us to perform complex data transformations on array fields. By combining it with other operators and stages in the aggregation framework, we can achieve a wide range of data analyses and manipulations.