Definição
Compatibilidade
Você pode utilizar o $cond para implantações hospedadas nos seguintes ambientes:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise: a versão autogerenciada e baseada em assinatura do MongoDB
MongoDB Community: uma versão com código disponível, de uso gratuito e autogerenciada do MongoDB
Sintaxe
The $cond expression has one of two syntaxes:
{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }
Ou:
{ $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.
Os argumentos podem ser qualquer expressãoválida.
Dica
Exemplos
Os exemplos nesta página usam dados do conjunto de dados sample_mflix. Para obter detalhes sobre como carregar este conjunto de dados em sua implantação do MongoDB autogerenciado, consulte Carregar o conjunto de dados de amostra. Se você fez alguma modificação nos bancos de dados de amostra, talvez seja necessário descartar e recriar os bancos de dados para executar os exemplos nesta página.
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 ] } } } ] )