Definition
Compatibility
You can use $cond for deployments hosted in the following
environments:
MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Syntax
The $cond expression has one of two syntaxes:
{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }
Or:
{ $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.
The arguments can be any valid expression. For more information on expressions, see Expressions.
Tip
Example
The examples on this page use data from the sample_mflix sample dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the sample dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.
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 ] } } } ] )