$ifNull (aggregation)

在本页面

Definition

$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" }
首页