定義
互換性
次の環境でホストされる配置には $cond を使用できます。
- MongoDB Atlas はクラウドでの MongoDB 配置のための完全管理サービスです
MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン
MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン
構文
The $cond expression has one of two syntaxes:
{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }
または:
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
$cond requires all three arguments (if-then-else) for either syntax.
If the <boolean-expression> evaluates to true, then $cond evaluates and returns the value of the <true-case> expression. Otherwise, $cond evaluates and returns the value of the <false-case> expression.
引数には任意の有効な式を使用できます。
Tip
例
このページの例では、sample_mflixサンプルデータセットのデータを使用します。このデータセットを自己管理型MongoDB配置にロードする方法の詳細については、サンプルデータセットをロードする を参照してください。サンプルデータベースに変更を加えた場合、このページの例を実行するには、データベースを削除して再作成する必要がある場合があります。
The following aggregation operation uses the $cond expression to assign a rental price to each movie. The operation prices movies with an imdb.rating greater than or equal to 9 at 5.99. The operation prices all other movies at 3.99:
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $project: { title: 1, rentalPrice: { $cond: { if: { $gte: [ "$imdb.rating", 9 ] }, then: 5.99, else: 3.99 } } } } ] )
[ { _id: ..., title: 'Baseball', rentalPrice: 5.99 }, { _id: ..., title: 'Centennial', rentalPrice: 3.99 } ]
The following operation uses the array syntax of the $cond expression and returns the same results:
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $project: { title: 1, rentalPrice: { $cond: [ { $gte: [ "$imdb.rating", 9 ] }, 5.99, 3.99 ] } } } ] )