Definition
Returns the n minimum values from documents in a specified window.
Note
Disambiguation
This page describes $minN when used as a window function.
You can also use $minN in these other contexts:
$minN (accumulator), which returns the minimumnvalues for each group.$minN (expression), which returns thenminimum values in an array.
Syntax
{ $setWindowFields: { ... output: { <field>: { $minN: { input: <expression>, n: <expression> } } } } }
Field | Type | Description |
|---|---|---|
| Expression | The |
| Expression | The number of elements that If the window contains fewer than |
Behavior
Type Comparison Order
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.
Example
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.
This example uses the $minN window function to return the two lowest IMDb ratings for each year.
db.movies.aggregate( [ { $match: { year: { $in: [ 1999, 2001 ] }, "imdb.rating": { $lte: 3.8, $gt: 0 } } }, { $setWindowFields: { partitionBy: "$year", output: { lowestTwoRatingsInYear: { $minN: { input: "$imdb.rating", n: 2 }, window: { documents: [ "unbounded", "unbounded" ] } } } } }, { $project: { _id: 0, title: 1, year: 1, "imdb.rating": 1, lowestTwoRatingsInYear: 1 } }, { $sort: { year: 1, "imdb.rating": 1 } } ] )
The preceding pipeline:
Uses
$matchto filter to movies from 1999 or 2001 with an IMDb rating of 3.8 or lower and greater than 0.Uses
$setWindowFieldsto partition movies byyear. The stage uses$minNwithn: 2to createlowestTwoRatingsInYearfrom a window defined asdocuments: [ "unbounded", "unbounded" ]. The window covers all documents in the partition, solowestTwoRatingsInYearshows the two lowest ratings for the entire year.Uses
$projectto include only thetitle,year,imdb.rating, andlowestTwoRatingsInYearfields in the output.Uses
$sortto order results by year andimdb.ratingin ascending order.