$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.
| Category | Accumulators |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (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
- Runs on server-side JavaScript, slower than native accumulators
- Callbacks must be serializable and cannot capture outer variables
- The merge callback combines group results in sharded or distributed setups
🏷️ Related Tags
💡 Related Cases
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.