- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $minN (aggregation accumulator)
$minN (aggregation accumulator)¶
On this page
Definition¶
-
$minN¶ New in version 5.2.
Returns an aggregation of the minimum value
nelements within a group. If the group contains fewer thannelements,$minNreturns all elements in the group.
Syntax¶
inputspecifies an expression that is the input to$minN. It is evaluated for each element in the group and$minNpreserves the minimumnvalues.nlimits the number of results per group andnhas to be a positive integral expression that is either a constant or depends on the_idvalue for$group.
Behavior¶
Null and Missing Values¶
$minNfilters out null and missing values.
Consider the following aggregation that returns the minimum n
documents from a group:
In this example:
$documentscreates the literal documents that contain player scores.$groupgroups the documents bygameId. This example has only onegameId,G1.PlayerDhas a missing score andPlayerEhas a nullscore. These values are both ignored.- The
minimumThreeScoresfield is specified as$minNwithinput : "$score"and returned as an array. - Since there are only 3 documents with
scoresminNreturns the minimum 3scorefields even thoughn = 4.
Restrictions¶
Window Function and Aggregation Expression Support¶
You can use $minN as an accumulator.
$minN is supported as an
aggregation expression.
$minN is supported as a
window operator.
Memory Limit Considerations¶
Aggregation pipelines which call $minN are subject to the
100 MB limit. If this
limit is exceeded for an individual group, the aggregation fails
with an error.
Examples¶
Consider a gamescores collection with the following documents:
Find the Minimum Three Scores for a Single Game¶
You can use the $minN accumulator to find the minimum three scores
in a single game.
The example pipeline:
- Uses
$matchto filter the results on a singlegameId. In this case,G1. - Uses
$groupto group the results bygameId. In this case,G1. - Specifies the fields that are input for
$minNwithinput : ["$score","$playerId"]. - Uses
$minNto return the first three score elements for theG1game withn : 3.
The operation returns the following results:
Finding the Minimum Three Documents Across Multiple Games¶
You can use the $minN accumulator to find the minimum n
scores in each game.
The example pipeline:
- Uses
$groupto group the results bygameId. - Uses
$minNto return the minimum three score elements for each game withn: 3. - Specifies the fields that are input for
$minNwithinput: ["$score","$playerId"].
The operation returns the following results:
Computing n Based on the Group Key for $group¶
You can also assign the value of n dynamically. In this example,
the $cond expression is used on the gameId field.
The example pipeline:
- Uses
$groupto group the results bygameId. - Specifies the fields that input for
$minNwithinput : ["$score","$playerId"]. - If the
gameIdisG2thennis 1, otherwisenis 3.
The operation returns the following results: