$ifNull
聚合运算符对输入表达式进行空值评估,并返回:
- 第一个非空表达式的值
- 将值为空的替换为指定的值
语法
{
$ifNull: [
<input-expression-1>,
...
<input-expression-n>,
<replacement-expression-if-null>
]
}
举例
使用下面的脚本创建inventory
集合:
db.inventory.insertMany( [
{ "_id" : 1, "item" : "buggy", description: "toy car", "quantity" : 300 },
{ "_id" : 2, "item" : "bicycle", description: null, "quantity" : 200 },
{ "_id" : 3, "item" : "flag" }
] )
单个表达式
db.inventory.aggregate(
[
{
$project: {
item: 1,
description: { $ifNull: [ "$description", "Unspecified" ] }
}
}
]
)
在本例中,使用$ifNull
返回:
- 非空的
description
字段 - 如果
description
字段的值为空或缺失返回"Unspecified"
字符串
结果如下:
{ "_id" : 1, "item" : "buggy", "description" : "toy car" }
{ "_id" : 2, "item" : "bicycle", "description" : "Unspecified" }
{ "_id" : 3, "item" : "flag", "description" : "Unspecified" }
多个表达式
注意: 5.0支持
下面的例子使用$ifNull
返回:
- 非空的
description
字段 - 如果
description
为空或缺失而且quantity
为非空,则返回quantity
- 如果
description
和quantity
都为空或缺失返回"Unspecified"
字符串
db.inventory.aggregate(
[
{
$project: {
item: 1,
value: { $ifNull: [ "$description", "$quantity", "Unspecified" ] }
}
}
]
)
结果如下:
{ "_id" : 1, "item" : "buggy", "value" : "toy car" }
{ "_id" : 2, "item" : "bicycle", "value" : 200 }
{ "_id" : 3, "item" : "flag", "value" : "Unspecified" }