On this page
$ifNull (aggregation)
在本页面
Definition
$ifNull
- 计算表达式,如果表达式的计算结果为非空值,则返回表达式的值。如果表达式的计算结果为空值,包括未定义值或缺少字段的实例,则返回替换表达式的值。
$ifNull表达式具有以下语法:
{ $ifNull: [ <expression>, <replacement-expression-if-null> ] }
参数可以是任何有效的expression。有关表达式的更多信息,请参见Expressions。
Example
以下示例将inventory
集合与以下文档一起使用:
{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 }
{ "_id" : 2, "item" : "abc2", description: null, qty: 200 }
{ "_id" : 3, "item" : "xyz1", qty: 250 }
以下操作使用$ifNull表达式返回非空description
字段值,或者如果description
字段为 null 或不存在,则返回字符串"Unspecified"
:
db.inventory.aggregate(
[
{
$project: {
item: 1,
description: { $ifNull: [ "$description", "Unspecified" ] }
}
}
]
)
该操作返回以下结果:
{ "_id" : 1, "item" : "abc1", "description" : "product 1" }
{ "_id" : 2, "item" : "abc2", "description" : "Unspecified" }
{ "_id" : 3, "item" : "xyz1", "description" : "Unspecified" }