Definition
Returns the n smallest values in an array.
Note
Disambiguation
This page describes $minN when used as an expression, which returns the n minimum values in an array.
You can also use $minN in these other contexts:
$minN (accumulator), which returns an aggregated value based on a variable number of input documents.$minN (window function), which is used in the$setWindowFieldsstage to return the minimumnvalues from documents in a particular window.
Syntax
{ $minN: { n: <expression>, input: <expression> } }
Field | Description |
|---|---|
| An expression that evaluates to a positive integer. The integer specifies the number of array elements that |
| An expression that evaluates to the array from which to return the minimum |
Behavior
You cannot specify a value of
nless than1.$minNfilters outnullvalues found in theinputarray.If the specified
nis greater than or equal to the number of elements in theinputarray,$minNreturns all elements in theinputarray.If
inputresolves to a non-array value, the expression produces an error.If
inputcontains elements of different types, comparisons across types follow the BSON comparison order.
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.
The following example uses the $minN operator to return the two alphabetically-first genres for each movie. The results are returned in the new field firstAlphabeticalGenres created by $addFields.
db.movies.aggregate( [ { $match: { $expr: { $gte: [ { $size: "$genres" }, 3 ] } } }, { $addFields: { firstAlphabeticalGenres: { $minN: { n: 2, input: "$genres" } } } }, { $project: { _id: 0, title: 1, genres: 1, firstAlphabeticalGenres: 1 } }, { $limit: 5 } ] )
The preceding pipeline:
Uses
$matchto filter for movies that have at least three genres.Uses
$addFieldsto create afirstAlphabeticalGenresfield.$minNwithn: 2returns the two alphabetically-first values from thegenresarray.Uses
$projectto return only thetitle,genres, andfirstAlphabeticalGenresfields.Uses
$limitto return five documents to improve readability.