Definition
$topNew 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. You can also use $top in these other contexts:
$top (accumulator), which returns the top element within a group according to the specified sort order.$top (window function), which is used in the$setWindowFieldsstage to return the top element from documents in a particular window.
Syntax
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 |
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 $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.