Learn the "why" behind slow queries and how to fix them in our 2-Part Webinar.
Register now >
Docs Menu
Docs Home
/ /

$top (expression operator)

$top

New in version 8.3.

Returns the top element within an array according to the specified sort order.

Note

Disambiguation

This page describes the $top expression operator. For the $top accumulator operator, see $top (accumulator operator).

When used as an expression operator, $top has the following syntax:

{
$top:
{
sortBy: <expression>,
input: <expression>
}
}
Field
Necessity
Description

sortBy

Required

Specifies the order of results. See Sort Behavior for more information on sortBy values.

input

Required

The array that $top evaluates.

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 errors.

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 $top on the cast array to return the first cast member in alphabetical order for a specified movie:

db.movies.aggregate([
{
$match: { title: "The Godfather" }
},
{
$project: {
_id: 0,
title: 1,
firstCastMemberAlphabetically: {
$top: {
sortBy: 1,
input: "$cast"
}
}
}
}
])
[
{
title: 'The Godfather',
firstCastMemberAlphabetically: 'Al Pacino'
}
]

In this example, $top sorts the existing cast array in ascending alphabetical order and returns the first value.

Back

$toObjectId

On this page