Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

$topN(式)

$topN

バージョン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.

注意

曖昧さ回避

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

式子として使用する場合、$topN は次の構文をとります。

{
$topN:
{
n: <expression>,
sortBy: <expression>,
input: <expression>
}
}
フィールド
必要性
説明

n

必須

返される配列要素の数。

sortBy

必須

結果の順序を指定します。 sortBy値の詳細については、「 ソート動作 」を参照してください。

入力

必須

$topN が評価する配列。

MongoDB はsortBy 値に基づいて input 配列をソートします。次の表に、さまざまなソートオプションの例を示します。

input
sortBy
ソート済み 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 }
]

inputフィールドは配列に変換される必要があります。配列ではない input を指定すると、 MongoDB はエラーを返します。

次の例では、movies sample_mflixサンプルデータセットの コレクションを使用します。このデータセットを配置にロードする方法の詳細については、「サンプルデータセットをロードする 」を参照してください。

moviesコレクションには、次の例のようなドキュメントが含まれています。

{
_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,
...
}

次の集計パイプラインでは、cast 配列で $topN を使用します。

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.

戻る

$top

項目一覧