MongoDB Accumulators

Beginner
⏱️ 14 min read
📚 Updated: Jul 2026
🎯 20 Tutorials
Aggregation

What you’ll learn

  • What MongoDB accumulators are and how they fit inside $group.
  • Which operator to pick for totals, arrays, ranked records, and custom logic.
  • A suggested learning path from $sum through $topN.
  • How to combine multiple accumulators in one grouping stage.
  • Links to every accumulator tutorial on CodeToFun (20 operators).

Prerequisites

Basic familiarity with MongoDB collections, the aggregation framework, and the $group stage. Helpful background: $match to filter before grouping and $sort when order affects $first / $last results.

  • $group basics: the _id expression defines buckets; other fields use accumulators.
  • Field paths: "$amount" refers to the current document’s field inside accumulators.
  • mongosh: run pipelines in the shell or Compass aggregation tab to verify output.
  • MongoDB 5.2+ for ranked accumulators ($top, $bottomN, etc.).

Key concepts

Every accumulator follows the same mental model: documents enter a group bucket, the operator updates state for each document, and one value is emitted per group.

Group buckets

_id can be a field, compound object, or null for one global group.

One output per group

Each accumulator field produces a single value (or array) per _id bucket.

Combine freely

One $group can run $sum, $avg, and $push together.

Filter first

Place $match before $group to shrink data and speed up aggregation.

Overview

Accumulators power analytics in MongoDB: revenue by store, average rating by product, unique tags per article, or the top three scores per class. Built-in operators cover most reports; $accumulator handles bespoke JavaScript when needed.

Numeric rollups

$sum, $avg, $min, $max, standard deviation.

Arrays & objects

$push, $addToSet, $mergeObjects.

Ranking

$top, $topN, $bottom, $bottomN with sortBy.

⚖️ Picking the right accumulator

Match the business question to the operator family before writing a pipeline.

GoalStart withNotes
Total revenue or quantity$sumUse { $sum: 1 } to count documents per group.
Average score or price$avgIgnores non-numeric values; returns null if none.
Every value in a list$pushKeeps duplicates and order (within group processing).
Unique tags or ids$addToSetSkips duplicates; order not guaranteed.
Best / worst full record$top / $bottomRequires sortBy; MongoDB 5.2+.
Top 3 leaderboard per group$topNReturns an array of up to N documents.
Custom business rule$accumulatorJavaScript; use only when built-ins fall short.
1

Multiple accumulators in one $group

A typical dashboard bucket: count orders, total revenue, average order size, and collect unique customer ids—all in one stage.

mongosh
db.orders.aggregate([
  { $match: { status: "completed" } },
  {
    $group: {
      _id: "$storeId",
      orderCount:  { $sum: 1 },
      revenue:     { $sum: "$amount" },
      avgOrder:    { $avg: "$amount" },
      customers:   { $addToSet: "$customerId" }
    }
  },
  { $sort: { revenue: -1 } }
]);

Suggested learning path

Work through tutorials in this order if you are new to MongoDB aggregation accumulators.

  1. Custom escape hatch: $accumulator — understand when JavaScript is needed.
  2. Arrays: $addToSet and $push for collecting values.
  3. Numeric core: $avg, $sum, $min, $max.
  4. Order: $first / $last and N-variant pages with $sort.
  5. Ranking: $top, $topN, $bottomN.
  6. Advanced numeric: $stdDevSamp and $mergeObjects.

Accumulator index

Every tutorial lives at /mongodb/accumulators/{slug}. Multi-word operators use kebab-case slugs (for example add-to-set, std-dev-pop).

Custom

OperatorWhat it does
$accumulatorCustom JavaScript with init, accumulate, merge, and finalize.

Numeric

OperatorWhat it does
$sumAdd numeric values or count documents with $sum: 1 per group.
$avgArithmetic mean of numeric field values in each bucket.
$minSmallest value of a single field across the group.
$maxLargest value of a single field across the group.
$minNArray of the N smallest numeric values (MongoDB 5.2+).
$maxNArray of the N largest numeric values (MongoDB 5.2+).
$stdDevPopPopulation standard deviation (divide by N).
$stdDevSampSample standard deviation (divide by N − 1).

Arrays & objects

OperatorWhat it does
$pushAppend every value into an array (duplicates allowed).
$addToSetCollect unique values into an array per group.
$mergeObjectsShallow-merge document objects; last duplicate key wins.

First / last (input order)

OperatorWhat it does
$firstFirst value seen in the group (depends on input order).
$firstNFirst N values as an array (use $sort first for ranked results).
$lastLast value seen in the group.
$lastNLast N values as an array.

Ranking (sortBy)

OperatorWhat it does
$topSingle top-ranked document per group using sortBy (5.2+).
$topNTop N ranked documents as an array (5.2+).
$bottomSingle bottom-ranked document per group (5.2+).
$bottomNBottom N ranked documents as an array (5.2+).

Pitfalls to avoid

$first

Unstable without $sort

$first and $last follow ingestion order unless you sort the stream first. For ranked results use $top / $topN.

$avg

String amounts skipped

Store numbers as numeric BSON types. String values like "120" are ignored by $sum and $avg.

$push

Memory growth

Large groups with $push can hit the 100 MB per-group limit. Filter with $match or aggregate in stages.

❓ FAQ

An accumulator is an operator used inside the $group stage to compute one output value per group bucket—totals, averages, arrays, ranked documents, or custom JavaScript rollups.
Primarily in $group: { _id: "$category", total: { $sum: "$amount" } }. Each accumulator processes every document that falls into the same _id bucket.
Accumulators aggregate across documents in a group. Expression operators like $add or $cond run per document inside $project or $addFields. Some names (e.g. $sum) exist in both forms with different syntax.
Start with $sum (totals and $sum: 1 counts), then $avg, $push, and $addToSet. Add $top/$bottom when you need ranked records inside each group.
Core operators ($sum, $avg, $push, etc.) are widely available. $top, $bottom, $topN, $bottomN, $firstN, $lastN, $minN, and $maxN require MongoDB 5.2 or later.
Use $accumulator only when built-in operators and expression combinations cannot express your rule. Built-ins are faster and easier to maintain for standard totals, means, and arrays.

Summary

  • Scope: 20 accumulator tutorials covering numeric, array, ranking, and custom operators.
  • Pattern: accumulators live inside $group and emit one value per bucket.
  • Next step: open MongoDB $accumulator Operator or pick any row from the index above.
Did you know?

The same aggregation stage can mix many accumulators—$sum, $avg, and $addToSet in one $group—because each output field maintains its own independent state per bucket. See the official $group accumulators list.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful