$reduce

Reference type:Cheat sheetFormat:Syntax + example + use case

Reference group: Array aggregation expressions

What it does

Folds an array into one result using $$value and $$this.

Syntax

{$reduce: { input, initialValue, in }}

Use case

Compute totals or custom accumulations.

$reduce: practical example
{ $project: { total: { $reduce: { input: "$items", initialValue: 0, in: { $add: ["$$value", { $multiply: ["$$this.price", "$$this.qty"] }] } } } } }
💡 Explanation Folds an array into one result using $$value and $$this. When to use it Compute totals or custom accumulations.
Key Takeaways
  • Folds an array into one result using $$value and $$this.
  • Typical use: Compute totals or custom accumulations.