- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $topN (aggregation accumulator)
$topN (aggregation accumulator)¶
On this page
Definition¶
-
$topN¶ New in version 5.2.
Returns an aggregation of the top
nelements within a group, according to the specified sort order. If the group contains fewer thannelements,$topNreturns all elements in the group.
Syntax¶
nlimits the number of results per group and has to be a positive integral expression that is either a constant or depends on the_idvalue for$group.- sortBy specifies the order of results, with syntax similar to
$sort. outputrepresents the output for each element in the group and can be any expression.
Behavior¶
Null and Missing Values¶
$topNdoes not filter out null values.$topNconverts missing values to null which are preserved in the output.
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. - Because of the
sortBy: { "score" : 1 }, the null values are sorted to the front of the returnedplayerIdarray.
BSON Data Type Sort Ordering¶
When sorting different types, the order of BSON data types is used to determine ordering. As an example, consider a collection whose values consist of strings and numbers.
- In an ascending sort, string values are sorted after numeric values.
- In a descending sort, string values are sorted before numeric values.
In this example:
PlayerAhas an integer score.PlayerBhas a string"2"score.PlayerChas an empty string score.
Because the sort is in descending { "score" : -1 }, the string
literal values are sorted before PlayerA’s numeric score:
Restrictions¶
Window Function and Aggregation Expression Support¶
$topN is not supported as a
aggregation expression.
$topN is supported as a
window operator.
Memory Limit Considerations¶
Groups within the $topN aggregation pipeline are subject to the
100 MB limit pipeline 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 Three Highest Scores¶
You can use the $topN accumulator to find the highest scoring
players 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. - Uses sort by
{ "score": -1 }to sort the results in descending order. - Specifies the fields that are output from
$topNwithoutput : ["$playerId"," $score"]. - Uses
$topNto return the top three documents with the highestscorefor theG1game withn : 3.
The operation returns the following results:
The SQL equivalent to this query is:
Finding the Three Highest Score Documents Across Multiple Games¶
You can use the $topN accumulator to find the highest scoring
players in each game.
The example pipeline:
- Uses
$groupto group the results bygameId. - Specifies the fields that are output from
$topNwithoutput : ["$playerId", "$score"]. - Uses sort by
{ "score": -1 }to sort the results in descending order. - Uses
$topNto return the top three documents with the highestscorefor each game withn: 3.
The operation returns the following results:
The SQL equivalent to this query is:
Computing n Based on the Group Key for $group¶
You can also assign the value of n dynamically. In this example,
the $cond expression is used on the gameId field.
The example pipeline:
- Uses
$groupto group the results bygameId. - Specifies the fields that are output from
$topNwithoutput : "$score". - If the
gameIdisG2thennis 1, otherwisenis 3. - Uses sort by
{ "score": -1 }to sort the results in descending order.
The operation returns the following results: