判断用的,可以跟if then 语句
可以发现,discount是我们新的键,它根据cond的if判断后,分别被赋上了相应的值(then和else可以省略)
1.举例
{ "_id" : 1, "item" : "abc1", qty: 300 }
{ "_id" : 2, "item" : "abc2", qty: 200 }
{ "_id" : 3, "item" : "xyz1", qty: 250 }
现在我们想根据qty的值来生成新的数据(值)
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 }
可以发现,discount是我们新的键,它根据cond的if判断后,分别被赋上了相应的值(then和else可以省略)