定義
$switch一連のケース式を評価します。
trueに評価される式が見つかると、$switch指定された式を実行し、制御フローを抜け出します。$switchの構文は次のとおりです。$switch: { branches: [ { case: <expression>, then: <expression> }, { case: <expression>, then: <expression> }, ... ], default: <expression> } branches配列内のオブジェクトには、caseフィールドとthenフィールドのみを含める必要があります。オペランド説明branchesdefault任意。
trueと評価するブランチcase式が無い場合に採用するパス。省略可能ですが、
defaultcaseが指定されず、 が true と評価するブランチ がない場合、$switchはエラーを返します。
動作
のさまざまなケース ステートメントは、相互に排他的である必要はありません。 $switchは、 trueと評価される最初に見つけたブランチを実行します。 どのブランチも true と評価しない場合、 $switchはdefaultオプションを実行します。
次の条件は、$switch がエラーで失敗する原因になります。
branchesフィールドが欠落しているか、少なくとも 1 つのエントリを含む配列ではありません。branches配列内のオブジェクトには、caseフィールドが含まれていません。branches配列内のオブジェクトには、thenフィールドが含まれていません。branches配列内のオブジェクトには、case以外、またはthen以外のフィールドが含まれています。defaultは指定されず、trueと評価されるcaseはありません。
例 | 結果 | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
| |||||||||
|
| |||||||||
|
|
例
grades という名前のコレクションには次のドキュメントが含まれています。
{ "_id" : 1, "name" : "Susan Wilkes", "scores" : [ 87, 86, 78 ] } { "_id" : 2, "name" : "Bob Hanna", "scores" : [ 71, 64, 81 ] } { "_id" : 3, "name" : "James Torrelio", "scores" : [ 91, 84, 97 ] }
次の集計操作では、$switch を使用して、各生徒の平均スコアに基づいて特定のメッセージが表示されます。
db.grades.aggregate( [ { $project: { "name" : 1, "summary" : { $switch: { branches: [ { case: { $gte : [ { $avg : "$scores" }, 90 ] }, then: "Doing great!" }, { case: { $and : [ { $gte : [ { $avg : "$scores" }, 80 ] }, { $lt : [ { $avg : "$scores" }, 90 ] } ] }, then: "Doing pretty well." }, { case: { $lt : [ { $avg : "$scores" }, 80 ] }, then: "Needs improvement." } ], default: "No scores found." } } } } ] )
この操作では、以下を返します。
{ "_id" : 1, "name" : "Susan Wilkes", "summary" : "Doing pretty well." } { "_id" : 2, "name" : "Bob Hanna", "summary" : "Needs improvement." } { "_id" : 3, "name" : "James Torrelio", "summary" : "Doing great!" }