0
0
MongodbHow-ToBeginner · 3 min read

How to Use $reduce in Aggregation in MongoDB

In MongoDB aggregation, $reduce is used to iterate over an array and combine its elements into a single value by applying an expression. It requires input (the array), initialValue (starting value), and in (expression using $$value and $$this) to define how to accumulate results.
📐

Syntax

The $reduce operator has three main parts:

  • input: The array to process.
  • initialValue: The starting value for accumulation.
  • in: An expression that defines how to combine the current accumulated value ($$value) with the current array element ($$this).
json
{
  $reduce: {
    input: <array>,
    initialValue: <any>,
    in: <expression>
  }
}
💻

Example

This example sums all numbers in an array field called values for each document.

mongodb
db.collection.aggregate([
  {
    $project: {
      total: {
        $reduce: {
          input: "$values",
          initialValue: 0,
          in: { $add: ["$$value", "$$this"] }
        }
      }
    }
  }
])
Output
[ { "_id": 1, "total": 15 }, { "_id": 2, "total": 10 } ]
⚠️

Common Pitfalls

Common mistakes when using $reduce include:

  • Not using $$value and $$this correctly inside the in expression.
  • Setting initialValue to a wrong type that does not match the expected result.
  • Using $reduce on a field that is not an array, which causes errors.

Always ensure the input is an array and the in expression properly combines $$value and $$this.

json
/* Wrong usage: missing $$value */
{
  $reduce: {
    input: "$values",
    initialValue: 0,
    in: { $add: ["$$this"] }  // Error: missing $$value
  }
}

/* Correct usage: include $$value */
{
  $reduce: {
    input: "$values",
    initialValue: 0,
    in: { $add: ["$$value", "$$this"] }
  }
}
📊

Quick Reference

PartDescription
inputThe array to iterate over
initialValueStarting value for accumulation
inExpression combining $$value (accumulated) and $$this (current element)

Key Takeaways

Use $reduce to combine array elements into a single value in aggregation.
Always provide input array, initialValue, and an in expression using $$value and $$this.
Ensure the input is an array to avoid errors.
The in expression defines how to accumulate results step-by-step.
Common errors come from missing $$value or wrong initialValue types.