mongo_aggregate_cond

mongo按条件返回字段值

假设数据库表inventory中的数据如下:

1
2
3
{ "_id" : 1, "item" : "abc1", "discount" : 30 }
{ "_id" : 2, "item" : "abc2", "discount" : 20 }
{ "_id" : 3, "item" : "xyz1", "discount" : 30 }

执行aggregate操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
db.inventory.aggregate(
[
{
$project:
{
item: 1,
discount:
{
$cond: { if: { $gte: [ "$qty", 250 ] }, then: 30, else: 20 }
}
}
}
]
)

或者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
db.inventory.aggregate(
[
{
$project:
{
item: 1,
discount:
{
$cond: [ { $gte: [ "$qty", 250 ] }, 30, 20 ]
}
}
}
]
)

返回结果:

{ “_id” : 1, “item” : “abc1”, “discount” : 30 }
{ “_id” : 2, “item” : “abc2”, “discount” : 20 }
{ “_id” : 3, “item” : “xyz1”, “discount” : 30 }

粤ICP备18054847号-2
本站总访问量次 本站访客数人 本文总阅读量
{% if theme.baidu_push %} {% endif %}