Definition
Returns the minimum n values within a group. If the group contains fewer than n elements, $minN returns all elements in the group.
Note
Disambiguation
This page describes $minN when used as an accumulator. Accumulators return an aggregated value like sum, maximum, or minimum across a group of input documents.
You can also use $minN in these other contexts:
$minN (expression), which returns thenminimum values in an array.$minN (window function), which is used in the$setWindowFieldsstage to return the minimumnvalues from documents in a particular window.
Syntax
{ $minN: { input: <expression>, n: <expression> } }
Field | Type | Description |
|---|---|---|
| Expression | An expression evaluated for each input document to determine the input values. The smallest |
| Expression | Determines the maximum number of results returned per group. |
Behavior
Result Type
When $minN compares values of different types, the ordering of types follows the BSON comparison order.
Null and Missing Values
$minN filters out null and missing values.
Consider the following aggregation that returns the minimum n values from a group:
db.aggregate( [ { $documents: [ { playerId: "PlayerA", gameId: "G1", score: 1 }, { playerId: "PlayerB", gameId: "G1", score: 2 }, { playerId: "PlayerC", gameId: "G1", score: 3 }, { playerId: "PlayerD", gameId: "G1" }, { playerId: "PlayerE", gameId: "G1", score: null } ] }, { $group: { _id: "$gameId", minimumThreeScores: { $minN: { input: "$score", n: 4 } } } } ] )
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
scores,$minNreturns the minimum 3scorefields even thoughn = 4.
[ { _id: 'G1', minimumThreeScores: [ 1, 2, 3 ] } ]
Comparison of $minN and $bottomN Accumulators
Both $minN and $bottomN accumulators return n values from a group, but they differ in how they determine which values to return.
Use
$minNwhen the values you want to compare are the same values you want to return.$minNselects thensmallest values by comparing inputs directly.Use
$bottomNwhen you want to define the sort order separately from the output.$bottomNlets you specify asortBykey to determine which documents are "bottom" and anoutputexpression to control what values to return.
Examples
The examples on this page use data from the sample_mflix dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the Sample Dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
Find the Minimum Three Ratings for a Single Genre
You can use the $minN accumulator to find the three lowest IMDb ratings in a single genre.
db.movies.aggregate( [ { $match: { genres: "Horror" } }, { $group: { _id: "Horror", minThreeRatings: { $minN: { input: "$imdb.rating", n: 3 } } } } ] )
The example pipeline:
Uses
$matchto filter the results to movies whereHorroris included in thegenresarray.Uses
$groupto group all matching documents into a single group.Specifies the input for
$minNwithinput: "$imdb.rating".Uses
$minNto return the three lowest IMDb rating entries for theHorrorgenre withn: 3.
Find the Minimum Three Ratings Across Multiple Genres
You can use the $minN accumulator to find the minimum n IMDb ratings in each genre.
db.movies.aggregate( [ { $unwind: "$genres" }, { $group: { _id: "$genres", minThreeRatings: { $minN: { input: "$imdb.rating", n: 3 } } } }, { $sort: { _id: 1 } }, { $limit: 5 } ] )
The example pipeline:
Uses
$unwindto create a separate document for each genre in thegenresarray.Uses
$groupto group the results bygenres.Uses
$minNto return the three lowest IMDb rating entries for each genre withn: 3.Specifies the input for
$minNwithinput: "$imdb.rating".Uses
$sortto sort the results alphabetically by genre.Limits the output to five documents to improve readability.
Set n Dynamically Based on the Group Key
You can assign the value of n dynamically. In this example, the $cond expression is used on the rated field.
db.movies.aggregate( [ { $match: { rated: { $in: [ "G", "PG", "PG-13", "R" ] } } }, { $group: { _id: { "rated": "$rated" }, minMovies: { $minN: { input: "$imdb.rating", n: { $cond: { if: { $eq: [ "$rated", "R" ] }, then: 3, else: 1 } } } } } } ] )
The example pipeline:
Filters for movies with ratings of
G,PG,PG-13, orR.Groups movies by
rated(the content rating).Specifies the input for
$minNwithinput: "$imdb.rating".Uses the
$condexpression to return3minimum entries forR-rated movies and1minimum entry for all other ratings.
In the output, the R rating returns 3 entries, while G, PG, and PG-13 ratings each return 1 entry.