$reduce (Reduce Array to Single Value)

Last updated: 2026-10-09

$reduce (Reduce Array to Single Value)

$reduce folds an array into a single value, the aggregation equivalent of functional reduce/fold. It takes an initialValue and an in expression where $$value is the accumulator and $$this is the current element. Typical uses: summing an array of numbers, joining strings, or counting elements that satisfy a condition. An empty array returns initialValue directly. $reduce is more general than $sum or $concat and can express arbitrary accumulation logic.

CategoryArray
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $reduce: { input: <array>, initialValue: <initialValue>, in: <reducer> } }

⚙️ Parameters

inputThe array to reduce.
initialValueThe starting value of the accumulator.
inThe reducer expression; $$value is the accumulator, $$this the current element.

Returns:A single reduced value; empty array returns initialValue; null input yields null

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $reduce: sum the array
db.stats.aggregate([
  { $project: {
      total: { $reduce: { input: '$scores', initialValue: 0, in: { $add: ['$$value', '$$this'] } } }
  } }
])

Output:

{ '_id': 1, 'total': 285 }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QCan $reduce sum an array?
AYes — initialValue 0 with { $add: ['$$value', '$$this'] }; for plain numbers $sum works too.
QWhat happens with an empty array?
AIt returns initialValue directly, without error.
QWhat are $$value and $$this?
A$$value is the running result and $$this the current element; both exist only inside $reduce's in.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏