- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $top (aggregation accumulator)
$top (aggregation accumulator)¶
On this page
Definition¶
-
$top¶ New in version 5.2.
Returns the top 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 top document from a group of scores:
$topdoes not filter out null values.$topconverts missing values to null.
In this example:
$documentscreates the literal documents that contain player scores.$groupgroups the documents bygameId. This example has only onegameId,G1.PlayerDhas a missing score andPlayerEhas a nullscore. These values are both considered as null.- The
playerIdandscorefields are specified asoutput : ["$playerId"," $score"]and returned as array values. - Specify the sort order with
sortBy: { "score": 1 }. PlayerDandPlayerEtied for the top element.PlayerDis returned as the topscore.- To have more deterministic tie breaking behavior for multiple null values, add more fields to``sortBy``.
Restrictions¶
Window Function and Aggregation Expression Support¶
$top is not supported as a
aggregation expression.
$top is supported as a
window operator.
Memory Limit Considerations¶
Aggregation pipelines which call $top 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 Top Score¶
You can use the $top accumulator to find the top score in a
single game.
The example pipeline:
- Uses
$matchto filter the results on a singlegameId. In this case,G1. - Uses
$groupto group the results bygameId. In this case,G1. - Specifies the fields that are output for
$topwithoutput : ["$playerId"," $score"]. - Uses
sortBy: { "score": -1 }to sort the scores in descending order. - Uses
$topto return the top score in the game.
The operation returns the following results:
Find the Top Score Across Multiple Games¶
You can use the $top accumulator to find the top score
in each game.
The example pipeline:
- Uses
$groupto group the results bygameId. - Uses
$topto return topscorefor each game. - Specifies the fields that are output for
$topwithoutput : ["$playerId", "$score"]. - Uses
sortBy: { "score": -1 }to sort the scores in descending order.
The operation returns the following results: