Definition
Returns the bottom element within a window according to the specified sort order.
Note
Disambiguation
This page describes $bottom when used as a window function. You can also use $bottom in these other contexts:
$bottom (expression operator), which returns the last element of an array based on a specified sort order.$bottom (accumulator), which returns the bottom element within a group according to the specified sort order.
Syntax
{ $setWindowFields: { ... output: { <field>: { $bottom: { sortBy: { <field1>: <sort order>, <field2>: <sort order> ... }, output: <expression> } } } } }
Field | Necessity | Description |
|---|---|---|
sortBy | Required | Defines the ranking order of elements within the window, with syntax similar to |
output | Required | Specifies the output for each element in the window. Can be any expression. |
Behavior
Null and Missing Values
$bottomdoes not filter out null values.$bottomconverts missing values to null.
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.
Compute Relative Rating to Lowest-Rated Movie Over a Window
This example uses $bottom as a window function to compute the rating of the current document relative to the lowest-rated movie in the same year. Each movie document contains that movie's rating and a calculated field showing how much higher the movie's rating is compared to the lowest-rated movie from the same year.
db.movies.aggregate( [ { $match: { year: { $in: [ 1980, 1981, 1982 ] }, "imdb.rating": { $exists: true, $ne: null }, genres: "Family", rated: "PG" } }, { $setWindowFields: { partitionBy: "$year", output: { lowestRatedInYear: { $bottom: { output: { title: "$title", rating: "$imdb.rating" }, sortBy: { "imdb.rating": -1 } }, window: { documents: [ "unbounded", "unbounded" ] } } } } }, { $project: { _id: 0, title: 1, year: 1, rating: "$imdb.rating", lowestRatedInYear: 1, ratingAboveWorst: { $subtract: [ "$imdb.rating", "$lowestRatedInYear.rating" ] } } }, { $limit: 10 } ] )
In this example:
The
$matchstage filters for PG-rated Family movies from 1980-1982.$setWindowFieldspartitions the documents byyear.The window spans from
unboundedtounbounded, meaning$bottomconsiders all documents in the partition when determining the lowest-rated movie.$bottomreturns the lowest-rated movie in each partition as an embedded document containing thetitleandratingfields.$projectcomputesratingAboveWorstby subtracting the lowest rating from each movie's rating, showing how much each movie is rated above the worst performer in its year.$limitlimits the output to 10 documents.
This approach preserves all individual movie documents and includes a comparison for each to the worst performer in its year.