$accumulator (Custom Accumulator)

Last updated: 2026-10-09

$accumulator (Custom Accumulator)

$accumulator defines custom accumulator logic with JavaScript callbacks — init, accumulate, merge, finalize — inside $group. It covers aggregation logic that built-in accumulators cannot express. It runs server-side JavaScript and is slower than native accumulators.

CategoryAccumulators
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $accumulator: { init: <function>, accumulate: <function>, accumulateArgs: [ <expression> ], merge: <function>, finalize: <function>, lang: "js" } }

Returns:Custom accumulation result (type decided by your functions)

▶ Example

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

// $accumulator: count distinct prices per item with a Set
db.sales.aggregate([
  { $group: { _id: '$item', uniq: {
    $accumulator: {
      init: function() { return new Set(); },
      accumulate: function(set, v) { set.add(v); },
      accumulateArgs: ['$price'],
      merge: function(a, b) { for (var v of b) a.add(v); },
      finalize: function(set) { return set.size; },
      lang: 'js'
    }
  } }
])

Output:

// Count of distinct prices per item

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QHow fast is $accumulator?
AIt runs server-side JS and is slower than native accumulators; avoid it when possible.
QWhich callbacks are required?
Ainit, accumulate, and accumulateArgs are required; merge and finalize are optional.
QWhat if the server does not support JavaScript?
AIt errors; an administrator must enable server-side scripting first.
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%

🙏 帮我们做得更好

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

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