- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $bottom (aggregation accumulator)
$bottom (aggregation accumulator)¶
On this page
Definition¶
-
$bottom
¶ New in version 5.2.
Returns the bottom element within a group according to the specified sort order.
Syntax¶
Field | Necessity | Description |
---|---|---|
sortBy | Required | Specifies the order of results, with syntax similar to
$sort . |
output | Required | Represents the output for each element in the group and can be any expression. |
Behavior¶
Null and Missing Values¶
Consider the following aggregation that returns the bottom document from a group of scores:
$bottom
does not filter out null values.$bottom
converts missing values to null.
In this example:
$documents
creates the literal documents that contain player scores.$group
groups the documents bygameId
. This example has only onegameId
,G1
.PlayerD
has a missing score andPlayerE
has a nullscore
. These values are both considered as null.- The
playerId
andscore
fields are specified asoutput : ["$playerId"," $score"]
and returned as array values. - Specify the sort order with
sortBy: { "score": -1 }
. PlayerD
andPlayerE
tied for the bottom element.PlayerD
is returned as the bottomscore
.- To have more deterministic tie breaking behavior for multiple null values, add more fields to``sortBy``.
Restrictions¶
Window Function and Aggregation Expression Support¶
$bottom
is not supported as a
aggregation expression.
$bottom
is supported as a
window operator
.
Memory Limit Considerations¶
Aggregation pipelines which call $bottom
are subject to the
100 MB limit. If this
limit is exceeded for an individual group, the aggregation fails
with an error.
Examples¶
Consider a gamescores
collection with the following documents:
Find the Bottom Score
¶
You can use the $bottom
accumulator to find the bottom score in a
single game.
The example pipeline:
- Uses
$match
to filter the results on a singlegameId
. In this case,G1
. - Uses
$group
to group the results bygameId
. In this case,G1
. - Specifies the fields that are output for
$bottom
withoutput : ["$playerId"," $score"]
. - Uses
sortBy: { "score": -1 }
to sort the scores in descending order. - Uses
$bottom
to return the bottom score for the game.
The operation returns the following results:
Finding the Bottom Score
Across Multiple Games¶
You can use the $bottom
accumulator to find the bottom score
in each game.
The example pipeline:
- Uses
$group
to group the results bygameId
. - Uses
$bottom
to return the bottomscore
for each game. - Specifies the fields that are output for
$bottom
withoutput : ["$playerId", "$score"]
. - Uses
sortBy: { "score": -1 }
to sort the scores in descending order.
The operation returns the following results: