Definition
$topNNew in version 8.3.
Returns the top
nelements of an array according to the specified sort order. If the array contains fewer thannelements,$topNreturns all elements in the array.
Note
Disambiguation
This page describes the $topN expression operator. For the $topN
accumulator operator, see $topN (accumulator operator).
Syntax
When used as an expression operator, $topN has the following syntax:
{ $topN: { n: <expression>, sortBy: <expression>, input: <expression> } }
Field | Necessity | Description |
|---|---|---|
n | Required | The number of array elements to return. |
sortBy | Required | Specifies the order of results. See Sort Behavior for more
information on |
input | Required | The array that |
Behavior
Sort Behavior
MongoDB sorts the input array based on the sortBy value. The following
table provides examples of different sort options:
input | sortBy | Sorted input | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| | ||||||||||
|
| | ||||||||||
|
| |
Input Values
The input field must resolve to an array. If you specify an input that is not
an array, MongoDB errors.
Example
The following example uses the movies collection from the sample_mflix
sample dataset. For details on how to load this dataset into
your deployment, see Load the sample dataset.
The movies collection contains documents that resemble the following
example:
{ _id: ObjectId('573a1396f29313caabce4a9a'), year: 1972, genres: [ 'Crime', 'Drama' ], title: 'The Godfather', cast: [ 'Marlon Brando', 'Al Pacino', 'James Caan', 'Richard S. Castellano' ], directors: [ 'Francis Ford Coppola' ], runtime: 175, ... }
The following aggregation pipeline uses $topN on the
cast array:
db.movies.aggregate([ { $match: { title: "The Godfather" } }, { $project: { _id: 0, title: 1, firstThreeCastMembersAlphabetically: { $topN: { n: 3, sortBy: 1, input: "$cast" } } } } ])
[ { title: 'The Godfather', firstThreeCastMembersAlphabetically: [ 'Al Pacino', 'James Caan', 'Marlon Brando' ] } ]
In this example, $topN sorts the existing cast array in ascending
alphabetical order and returns the first three values.