参考 > 参考 > 经营者 > 聚合管道运营商 > $ ifNull(聚合)
在本页面
$ifNull
计算表达式,如果表达式的计算结果为非空值,则返回表达式的值。如果表达式的计算结果为空值,包括未定义值或缺少字段的实例,则返回替换表达式的值。
该$ifNull表达式具有以下语法:
{ $ifNull: [ <expression>, <replacement-expression-if-null> ] }
参数可以是任何有效的表达式。有关表达式的更多信息,请参见 表达式。
以下示例将inventory集合与以下文档一起使用:
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字段值或"Unspecified"如果description字段为空或不存在的字符串 :
description
"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" }