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

$topN (expression operator)

$topN

New in version 8.3.

Returns the top n elements of an array according to the specified sort order. If the array contains fewer than n elements, $topN returns all elements in the array.

Note

Other Uses of $topN

This page describes $topN when used as an expression, which operates on array values.

You can also use $topN in these other contexts:

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 sortBy values.

input

Required

The array that $topN evaluates.

  • $topN does not filter out null values.

  • $topN converts missing values to null.

MongoDB sorts the input array based on the sortBy value. The following table provides examples of different sort options:

input
sortBy
Sorted input
[ 8, 3, 1, 10]

1

[1, 3, 8, 10]
[ 8, 3, 1, 10]

-1

[10, 8, 3, 1]
[
{ a: 1, b: 1 },
{ a: 2, b: 2 },
{ a: 2, b: 1 }
]

{ a: 1, b: 1 }

[
{ a: 1, b: 1 },
{ a: 2, b: 1 },
{ a: 2, b: 2 }
]

The input field must resolve to an array. If you specify an input that is not an array, MongoDB returns an error.

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.