定義
指定ソート順に従って、グループ内の最下位の要素を返します。
次のステージで使用できます。
注意
曖昧さ回避
このページでは、アキュムレータとして使用する場合の$bottom について説明します。アキュムレータは、入力ドキュメントのグループにわたる単一の集計値を返します。
$bottom (window function)$setWindowFieldsまた、特定のウィンドウ内のドキュメントから最下位の要素を返すには、 ステージで を使用します。
構文
{ $bottom: { sortBy: { <field1>: <sort order>, <field2>: <sort order> ... }, output: <expression> } }
フィールド | 必要性 | 説明 |
|---|---|---|
sortBy | 必須 | 各グループ内の要素のランキング順序を定義します。構文は |
出力 | 必須 | グループ内の各要素の出力を表し、任意の 式 にすることができます。 |
動作
NULL および欠損値
$bottom は null 値をフィルタリングで除外せず、$bottom は欠落値を null に変換します。
スコアのグループから最下位のドキュメントを返す次の集計を検討します。
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アキュムレータを使用すると、単一のジャンル内で最も評価の低い映画を見つけることができます。
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 } } ] )
サンプル パイプライン: