MongoDB $maxN Accumulator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $maxN?

$maxN is a MongoDB accumulator for the $group stage (MongoDB 5.2+). For each group it returns an array of the N largest input values—no separate $sort stage required.

Remember
$maxN = N largest values per group (as an array)

input → expression to compare (e.g. "$score")
n     → how many maximums to keep

null / missing → filtered out (not compared)
vs $max  → one peak value
vs $topN → ranks full documents with sortBy
UsePrefer
Top N numeric values$maxN
Single highest value$max
Top N documents with sortBy$topN

How to Use $maxN in MongoDB

Two keys drive every call: input and n.

  1. Put $maxN inside $group on an output field.
  2. Set input to the field or expression to compare (or an array of fields).
  3. Set n to how many largest values to keep.
  4. Choose _id for the group key (class, game, or null).
KeyRequired?Role
inputYesExpression (or array of expressions) to maximize
nYesPositive integer (or expression based on group key)
$group._idYesGroup key ("$class", null, …)

Pseudocode

Pseudocode
for each group:
    values = []
    for each document in group:
        v = evaluate(input)
        if v is not null:
            values.append(v)
    keep = largest n values from values   // descending
    emit { _id: groupKey, field: keep }

Cheat Sheet

Keep these facts handy while collecting the largest N values.

TopicDetail
Stage$group accumulator (also expression / window form)
Syntax{ $maxN: { input: "$field", n: 3 } }
ReturnsArray of up to n largest values
null / missingFiltered out (not compared)
$sort needed?No—$maxN compares itself
VersionMongoDB 5.2+

Live Preview

Watch the top 2 scores per class. Sample: A/Sam 90, A/Ana 70, A/Lee 85, B/Mia 60, B/Omar 95, B/Zoe 88.

Simulates $maxN with input: "$score" and n: 2.

Result
class A scores: 90, 70, 85 → top 2 = [90, 85]
class B scores: 60, 95, 88 → top 2 = [95, 88]

[
  { _id: "A", topScores: [90, 85] },
  { _id: "B", topScores: [95, 88] }
]

Worked Walkthrough — Top 2 Scores

Six students, two classes. Keep the two highest scores in each class.

Calculation
Documents:
  { class: "A", student: "Sam",  score: 90 }
  { class: "A", student: "Ana",  score: 70 }
  { class: "A", student: "Lee",  score: 85 }
  { class: "B", student: "Mia",  score: 60 }
  { class: "B", student: "Omar", score: 95 }
  { class: "B", student: "Zoe",  score: 88 }

$maxN { input: "$score", n: 2 }

class "A": scores 90, 70, 85 → [90, 85]
class "B": scores 60, 95, 88 → [95, 88]

Output:
  { _id: "A", topScores: [90, 85] }
  { _id: "B", topScores: [95, 88] }

MongoDB Examples

We use a tiny scores collection. First we take the two highest scores per class. Then we return score + student pairs for those top values. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine six students. Each document has a class, student name, and score.

mongosh
db.scores.insertMany([
  { class: "A", student: "Sam", score: 90 },
  { class: "A", student: "Ana", score: 70 },
  { class: "A", student: "Lee", score: 85 },
  { class: "B", student: "Mia", score: 60 },
  { class: "B", student: "Omar", score: 95 },
  { class: "B", student: "Zoe", score: 88 }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps 6 documents in scores. Run find() to see them:

mongosh
db.scores.find()

Read each document like this:

Field in MongoDBMeaningExample
classClass / group name"B"
studentStudent name"Omar"
scoreTest score95
Picture
Class A scores: 90, 70, 85
Class B scores: 60, 95, 88

Next: $maxN keeps the N largest scores per class.

How It Works

  1. Insert once. The sample command adds 6 documents to scores.
  2. MongoDB stores fields as written. Each document keeps the same field names and values you inserted.
  3. find() shows the same shape. What you inserted is what you get back—ready for $maxN in the next examples.

Top 2 scores: class A → 90, 85; class B → 95, 88.

Example 2 — Top 2 Scores per Class

Goal: for each class, return an array of the two highest scores. No $sort stage—$maxN compares the values itself.

mongosh
db.scores.aggregate([
  {
    $group: {
      _id: "$class",
      topScores: {
        $maxN: {
          input: "$score",
          n: 2
        }
      }
    }
  },
  { $sort: { _id: 1 } }
]);

How It Works

  1. Split by class. _id: "$class" makes groups "A" and "B".
  2. Compare scores. input: "$score" is evaluated on every document in the group.
  3. Keep the largest n. With n: 2, class A keeps 90 and 85; 70 is dropped.
  4. Array result. Unlike $max, you get a list—not a single number.
  5. Nulls are skipped. If a score were missing or null, it would not compete for a slot.

Example 3 — Top 2 with Student Name

Goal: keep the student who owns each top score. Pass an array as input so each element is [score, student]. Comparison uses BSON order—score first, then student.

mongosh
db.scores.aggregate([
  {
    $group: {
      _id: "$class",
      topPlayers: {
        $maxN: {
          // Compare [score, student]; largest pairs win
          input: ["$score", "$student"],
          n: 2
        }
      }
    }
  },
  { $sort: { _id: 1 } }
]);

How It Works

  1. Same groups. Still one bucket per class.
  2. Richer input. Each document contributes [score, student] instead of a bare number.
  3. Largest pairs win. Class A keeps Sam (90) and Lee (85); Ana (70) drops out.
  4. Names travel with scores. Useful for leaderboards without a second lookup.
  5. Need full documents + sortBy? Prefer $topN.

Edge Cases & Pitfalls

Check these before shipping a top-N values report.

null

Null and missing are skipped

Unlike $firstN, nulls do not take a slot in the result array.

n

Fewer than n valid values is OK

The array is simply shorter. You never get padding for empty slots.

ties

Ties may need $topN

When you need a guaranteed order among equal values, use $topN with an explicit sortBy.

version

Requires MongoDB 5.2+

Older servers lack $maxN. Fallback: $sort + $group with $push, then slice.

Performance Notes

ApproachCostBest for
$maxNTracks up to n max values per groupTop-N scalars without a prior sort
$maxTracks one valueSingle peak only
$topNRanks with sortByDocuments + stable ordering

Prefer $max when one number is enough. Keep n small and filter early with $match. Large groups are still subject to the aggregation memory limit.

Key Takeaways

  • Role: array of the N largest input values per group.
  • Keys: input + n (both required).
  • Nulls: filtered out; short groups return fewer than n.
  • vs $topN: max values vs ranked documents with sortBy.

One line: $maxN keeps the largest N values per group—ideal for simple top-N score lists.

Frequently Asked Questions

$maxN returns an array of the N largest input values from each $group bucket. It compares values across the group and keeps the top N—no $sort stage is required.
Inside $group: { topThree: { $maxN: { input: "$score", n: 3 } } }. Both input and n are required. It also works as an aggregation expression and window operator.
$max returns a single highest value. $maxN returns an array of up to N highest values. Use $max for the peak alone; use $maxN for a short top-N list of scores or prices.
$maxN finds the N maximum values by comparison without sortBy. $topN ranks inside $group with sortBy and returns top N documents. Prefer $topN when you need a guaranteed sort order on ties.
No. Unlike $firstN and $lastN, $maxN filters out null and missing values. If only three documents have scores and n is 4, you get an array of three elements.
$maxN returns all available non-null values—never more than exist. A group with two numeric scores and n: 3 yields an array of two items.

Next: $mergeObjects

Merge documents into one object while grouping.

$mergeObjects tutorial →

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