このバージョンのドキュメントはアーカイブされており、サポートされなくなりました。6.0 配置をアップグレードするには、 MongoDB 7.0 のアップグレード手順 を参照してください。
定義
互換性
次の環境でホストされる配置には $cond を使用できます。
MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです
MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン
MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン
構文
$cond 式は次の 2 つの構文のいずれかをとります。
{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }
または:
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
$cond はいずれの構文でも 3 つのすべての引数(if-then-else)を必要とします。
<boolean-expression> が true と評価された場合、$cond は<true-case> 式の値を評価して返します。それ以外の場合、$cond は <false-case> 式の値を評価して返します。
引数には任意の有効な式を使用できます。 式の詳細については、「式 」を参照してください。
Tip
例
次の例では、以下のドキュメントを含む inventory コレクションを使用しています。
db.inventory.insertMany( [ { _id: 1, item: "abc1", qty: 300 }, { _id: 2, item: "abc2", qty: 200 }, { _id: 3, item: "xyz1", qty: 250 } ] )
次の集計操作では $cond 式を使用して、qty の値が 250 以上である場合は discount の値を 30 に設定し、qty の値が 250 未満の場合は 20 に設定します。
db.inventory.aggregate( [ { $project: { item: 1, discount: { $cond: { if: { $gte: [ "$qty", 250 ] }, then: 30, else: 20 } } } } ] )
この操作は次の結果を返します。
{ _id: 1, item: "abc1", discount: 30 } { _id: 2, item: "abc2", discount: 20 } { _id: 3, item: "xyz1", discount: 30 }
次の操作では、$cond 式の配列構文を使用して、同じ結果を返します。
db.inventory.aggregate( [ { $project: { item: 1, discount: { $cond: [ { $gte: [ "$qty", 250 ] }, 30, 20 ] } } } ] )