定義
$topNバージョン8.3の新機能。
Returns the top
nelements of an array according to the specified sort order. If the array contains fewer thannelements,$topNreturns 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> } }
動作
ソート動作
MongoDB はsortBy 値に基づいて input 配列をソートします。次の表に、さまざまなソートオプションの例を示します。
input | sortBy | ソート済み input | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| | ||||||||||
|
| | ||||||||||
|
| |
Input Values
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.