AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

$switch(集計式演算子)

$switch

一連のケース式を評価します。trueに評価される式が見つかると、 $switch指定された式を実行し、制御フローを抜け出します。

$switch の構文は次のとおりです。

$switch: { branches: [ { case: <expression>, then: <expression> }, { case: <expression>, then: <expression> }, ... ], default: <expression>}

branches 配列内のオブジェクトには、case フィールドと then フィールドのみを含める必要があります。

オペランド
説明

branches

制御ブランチ ドキュメントの配列。各ブランチは、次のフィールドを持つドキュメントです。

  • case
    boolean に変換される任意の有効な式を指定できます。結果が boolean でない場合は、強制的にブール値になります。MongoDB が式を true または false として評価する方法の詳細については、こちらをご覧ください。
  • then
    任意の有効な式を指定できます。

branches 配列には少なくとも 1 つのブランチ ドキュメントが含まれる必要があります。

default

任意。true と評価するブランチ case 式が無い場合に採用するパス。

省略可能ですが、default が指定されず、true と評価するブランチ case がない場合、$switch はエラーを返します。

のさまざまなケース ステートメントは、相互に排他的である必要はありません。 $switchは、 trueと評価される最初に見つけたブランチを実行します。 どのブランチも true と評価しない場合、 $switchはdefaultオプションを実行します。

次の条件は、$switch がエラーで失敗する原因になります。

  • branches フィールドが欠落しているか、少なくとも 1 つのエントリを含む配列ではありません。

  • branches 配列内のオブジェクトには、case フィールドが含まれていません。

  • branches 配列内のオブジェクトには、then フィールドが含まれていません。

  • branches 配列内のオブジェクトには、 case 以外、または then 以外のフィールドが含まれています。

  • default は指定されず、true と評価されるcase はありません。

例
結果
{ $switch: { branches: [ { case: { $eq: [ 0, 5 ] }, then: "equals" }, { case: { $gt: [ 0, 5 ] }, then: "greater than" }, { case: { $lt: [ 0, 5 ] }, then: "less than" } ] }}

"less than"

{ $switch: { branches: [ { case: { $eq: [ 0, 5 ] }, then: "equals" }, { case: { $gt: [ 0, 5 ] }, then: "greater than" } ], default: "Did not match" }}

"Did not match"

{ $switch: { branches: [ { case: "this is true", then: "first case" }, { case: false, then: "second case" } ], default: "Did not match" }}

"First case"

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

この集計操作では、$switch を使用して、各映画の評価に基づいて特定のメッセージが表示されます。$match ステージでは、サンプルデータセット内の最も長い3つの映画に結果を制限します。

db.movies.aggregate( [ { $match: { runtime: { $gt: 800 } } }, { $project: { _id: 0, title: 1, summary: { $switch: { branches: [ { case: { $gte: [ "$imdb.rating", 9 ] }, then: "Doing great!" }, { case: { $and: [ { $gte: [ "$imdb.rating", 8 ] }, { $lt: [ "$imdb.rating", 9 ] } ] }, then: "Doing pretty well." }, { case: { $lt: [ "$imdb.rating", 8 ] }, then: "Needs improvement." } ], default: "No rating found." } } } }, { $sort: { title: 1 } }] )
[ { title: 'Baseball', summary: 'Doing great!' }, { title: 'Centennial', summary: 'Doing pretty well.' }, { title: 'Taken', summary: 'Needs improvement.' }]
このページを評価

項目一覧