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

$bottomN (expression operator)

$bottomN

New in version 8.3.

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

Note

Disambiguation

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

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

{ $bottomN: { n: <expression>, sortBy: { <field1>: <sort order>, <field2>: <sort order> ... }, 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.

input

Required

The array that $bottomN 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 $bottomN on the cast array:

db.movies.aggregate([ { $match: { title: "The Godfather" } }, { $project: { _id: 0, title: 1, lastThreeCastMembersAlphabetically: { $bottomN: { n: 3, sortBy: 1, input: "$cast" } } } }])
[ { title: 'The Godfather', lastThreeCastMembersAlphabetically: [ 'James Caan', 'Marlon Brando', 'Richard S. Castellano' ] }]

In this example, $bottomN sorts the existing cast array in ascending alphabetical order and returns the last three values.