定義
指定ソート順に従って、グループ内の最下位の要素を返します。
次のステージで使用可能:
注意
曖昧さ回避
このページでは、$bottom をアキュムレータとして使用する場合について説明します。アキュムレータは、入力ドキュメントのグループ全体で単一の集計値を返します。
$bottom は、これらの他のコンテキストでも使用できます。
$bottom (expression operator), 指定されたソート順序に基づいて配列の最後の要素を返します。$bottom (window function)は、$setWindowFieldsステージで使用され、特定のウィンドウ内のドキュメントから最下部の要素を返します。
構文
{ $bottom: { sortBy: { <field1>: <sort order>, <field2>: <sort order> ... }, output: <expression> } }
フィールド | 必要性 | 説明 |
|---|---|---|
sortBy | 必須 | 各グループ内の要素のランキング順序を定義します。構文は、 |
出力 | 必須 | グループ内の各要素の出力を表し、任意の 式 にすることができます。 |
動作
NULL および欠損値
$bottom ヌル値をフィルターして除外しません。また、$bottom は欠落値をヌルに変換します。
スコアのグループから最下位のドキュメントを返す次の集計を検討します。
db.aggregate( [ { $documents: [ { playerId: "PlayerA", gameId: "G1", score: 1 }, { playerId: "PlayerB", gameId: "G1", score: 2 }, { playerId: "PlayerC", gameId: "G1", score: 3 }, { playerId: "PlayerD", gameId: "G1"}, { playerId: "PlayerE", gameId: "G1", score: null } ] }, { $group: { _id: "$gameId", playerId: { $bottom: { output: [ "$playerId", "$score" ], sortBy: { "score": -1 } } } } } ] )
[ { _id: 'G1', playerId: [ 'PlayerD', null ] } ]
この例では、次のことが行われます。
$documentsは、プレイヤーのスコアを含むリテラル ドキュメントを作成します。$groupはドキュメントをgameIdでグループ化します。 この例ではgameId、G1は 1 つのみです。PlayerDはスコアが欠落しており、PlayerEには nullscoreがあります。 これらの値は両方とも null と見なされます。playerIdフィールドとscoreフィールドはoutput : ["$playerId"," $score"]として指定され、配列値として返されます。ランキング順を
sortBy: { "score": -1 }で指定します。PlayerD最下位要素には とPlayerEが関連付けられています。PlayerDは最低のscoreとして返されます。
制限事項
メモリ制限に関する考慮事項
$bottomを呼び出す集計パイプラインには100 MB の制限が適用されます。 個々のグループでこの制限を超えると、集計はエラーで失敗します。
例
このページの例では、sample_mflix データセット のデータを使用しています。自己管理型 MongoDB 配置にこのデータセットをロードする方法の詳細については、「サンプル データセットのロード」を参照してください。サンプル データベースに何らかの変更を加えた場合は、今ページの例を実行するには、データベースを削除して再作成する必要がある可能性があります。
ジャンル内の最低評価を検索する
$bottom アキュムレータを使用すると、1 つのジャンル内の最低評価の映画を検索できます。
db.movies.aggregate( [ { $match : { genres: "Comedy" } }, { $group: { _id: "Comedy", lowestRatedMovie: { $bottom: { output: [ "$title", "$imdb.rating" ], sortBy: { "imdb.rating": -1 } } } } } ] )
サンプル パイプライン:
複数年にわたって最下位の評価を見つける
$bottom アキュムレータを使用すると、年度ごとに最低評価の映画を検索できます。
db.movies.aggregate( [ { $match: { "imdb.rating": { $exists: true }, year: { $gte: 2010, $lte: 2012 } } }, { $group: { _id: "$year", lowestRatedMovie: { $bottom: { output: [ "$title", "$imdb.rating" ], sortBy: { "imdb.rating": -1 } } } } }, { $sort: { _id: 1 } } ] )
サンプル パイプライン: