$cond (aggregation)
定义
{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }例子
最后更新于
{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }最后更新于
{ "_id" : 1, "item" : "abc1", qty: 300 }
{ "_id" : 2, "item" : "abc2", qty: 200 }
{ "_id" : 3, "item" : "xyz1", qty: 250 }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 }db.inventory.aggregate(
[
{
$project:
{
item: 1,
discount:
{
$cond: [ { $gte: [ "$qty", 250 ] }, 30, 20 ]
}
}
}
]
)