For AI agents: a documentation index is available at https://www.mongodb.com/es/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

$bottom (window function)

$bottom

New in version 5.2.

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:

{
$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 $sort. Does not affect the order of documents in pipeline output.

output

Required

Specifies the output for each element in the window. Can be any expression.

  • $bottom does not filter out null values.

  • $bottom converts missing values to null.

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 $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 $match stage filters for PG-rated Family movies from 1980-1982.

  • $setWindowFields partitions the documents by year.

  • The window spans from unbounded to unbounded, meaning $bottom considers all documents in the partition when determining the lowest-rated movie.

  • $bottom returns the lowest-rated movie in each partition as an embedded document containing the title and rating fields.

  • $project computes ratingAboveWorst by subtracting the lowest rating from each movie's rating, showing how much each movie is rated above the worst performer in its year.

  • $limit limits 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.