Definition
Returns the bottom n elements within a particular window, according to the specified sort order.
Note
Disambiguation
This page describes $bottomN when used as a window function.
You can also use $bottomN (accumulator), which returns the bottom n elements within a group according to the specified sort order.
Syntax
{ $setWindowFields: { ... output: { <field>: { $bottomN: { n: <expression>, output: <expression>, sortBy: { <field1>: <sort order>, <field2>: <sort order> ... } }, window: { documents: [ <lower boundary>, <upper boundary> ] } } } } }
Options
Field | Necessity | Description |
|---|---|---|
| Required | Number of results to return. Must resolve to a positive integral value. If the window contains fewer than |
| Required | Determines the output for each document in the window. Can be any expression. |
| Required | Defines the ranking order of elements within the window, with syntax similar to |
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.
Find the Three Lowest Rated Movies in a Window
This example uses the $bottomN window function to return each movie along with the three lowest-rated movies released in the same year.
db.movies.aggregate( [ { $unwind: "$genres" }, { $match: { genres: "Action", rated: "PG-13", "imdb.rating": { $lte: 5 }, year: { $in: [ 2000, 2001, 2002 ] } } }, { $setWindowFields: { partitionBy: "$year", output: { lowestThreeMovies: { $bottomN: { sortBy: { "imdb.rating": -1, title: 1 }, output: [ "$title", "$imdb.rating" ], n: 3 }, window: { documents: [ "unbounded", "unbounded" ] } } } } }, { $project: { _id: 0, title: 1, year: 1, "imdb.rating": 1, lowestThreeMovies: 1 } } ] )
In the preceding example:
$unwinddeconstructs thegenresarray so each movie document only contains a single genre.$matchrestricts the input toActionmovies that are ratedPG-13, have animdb.ratingvalue of 5 or less, and were released in 2000, 2001, or 2002.$setWindowFieldspartitions the documents byyear.window: { documents: [ "unbounded", "unbounded" ] }spans the entire year partition, so$bottomNconsiders all documents in the year when determining the three lowest-rated movies.$bottomNusessortBy: { "imdb.rating": -1, title: 1 }to rank movies by IMDb score and usestitleas a tie-breaker. Every document in the same year receives the samelowestThreeMoviesvalue.$projectremoves unneeded fields to highlight the window function result.