MongoDB $minN Accumulator

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

What Is $minN?

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

Remember
$minN = N smallest values per group (as an array)

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

null / missing → filtered out (not compared)
vs $min     → one floor value
vs $bottomN → ranks full documents with sortBy
vs $maxN    → N largest instead of N smallest
UsePrefer
Bottom N numeric values$minN
Single lowest value$min
Bottom N documents with sortBy$bottomN

How to Use $minN in MongoDB

Two keys drive every call: input and n.

  1. Put $minN 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 smallest values to keep.
  4. Choose _id for the group key (class, game, or null).
KeyRequired?Role
inputYesExpression (or array of expressions) to minimize
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 = smallest n values from values   // ascending
    emit { _id: groupKey, field: keep }

Cheat Sheet

Keep these facts handy while collecting the smallest N values.

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

Live Preview

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

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

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

[
  { _id: "A", lowScores: [70, 85] },
  { _id: "B", lowScores: [60, 88] }
]

Worked Walkthrough — Bottom 2 Scores

Six students, two classes. Keep the two lowest 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 }

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

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

Output:
  { _id: "A", lowScores: [70, 85] }
  { _id: "B", lowScores: [60, 88] }

MongoDB Examples

We use a tiny scores collection. First we take the two lowest scores per class. Then we return score + student pairs for those bottom 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"A"
studentStudent name"Ana"
scoreTest score70
Picture
Class A scores: 90, 70, 85
Class B scores: 60, 95, 88

Next: $minN keeps the N smallest 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 $minN in the next examples.

Bottom 2 scores: class A → 70, 85; class B → 60, 88.

Example 2 — Bottom 2 Scores per Class

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

mongosh
db.scores.aggregate([
  {
    $group: {
      _id: "$class",
      lowScores: {
        $minN: {
          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 smallest n. With n: 2, class A keeps 70 and 85; 90 is dropped.
  4. Array result. Unlike $min, 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 — Bottom 2 with Student Name

Goal: keep the student who owns each low 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",
      lowPlayers: {
        $minN: {
          // Compare [score, student]; smallest 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. Smallest pairs win. Class A keeps Ana (70) and Lee (85); Sam (90) drops out.
  4. Names travel with scores. Useful for “who needs help” reports without a second lookup.
  5. Need full documents + sortBy? Prefer $bottomN.

Edge Cases & Pitfalls

Check these before shipping a bottom-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 $bottomN

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

version

Requires MongoDB 5.2+

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

Performance Notes

ApproachCostBest for
$minNTracks up to n min values per groupBottom-N scalars without a prior sort
$minTracks one valueSingle floor only
$bottomNRanks with sortByDocuments + stable ordering

Prefer $min 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 smallest input values per group.
  • Keys: input + n (both required).
  • Nulls: filtered out; short groups return fewer than n.
  • vs $bottomN: min values vs ranked documents with sortBy.

One line: $minN keeps the smallest N values per group—ideal for simple bottom-N score lists.

Frequently Asked Questions

$minN returns an array of the N smallest input values from each $group bucket. It compares values across the group and keeps the bottom N—no $sort stage is required.
Inside $group: { lowestThree: { $minN: { input: "$score", n: 3 } } }. Both input and n are required. It also works as an aggregation expression and window operator.
$min returns a single lowest value. $minN returns an array of up to N lowest values. Use $min for the floor alone; use $minN for a short bottom-N list of scores or prices.
$minN finds the N minimum values by comparison without sortBy. $bottomN ranks inside $group with sortBy and returns bottom N documents. Prefer $bottomN when you need a guaranteed sort order on ties.
No. Like $maxN, $minN filters out null and missing values. If only three documents have scores and n is 4, you get an array of three elements.
$minN 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: $push

Append every value into an array for each group.

$push 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