判断用的,可以跟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可以省略)
本文介绍如何使用MongoDB的聚合框架实现条件判断,并通过一个具体示例展示如何根据库存数量(qty)的不同来生成不同的折扣率。此方法利用了$cond操作符配合ifthen语句来实现。
1541

被折叠的 条评论
为什么被折叠?



