$ifNull (aggregation)

On this page本页内容

Definition定义

$ifNull

Evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value. 计算表达式的值,如果表达式的计算结果为非null值,则返回表达式的值。If the expression evaluates to a null value, including instances of undefined values or missing fields, returns the value of the replacement expression.如果表达式的计算结果为空值,包括未定义值或缺少字段的实例,则返回替换表达式的值。

The $ifNull expression has the following syntax:$ifNull表达式语法如下所示:

{ $ifNull: [ <expression>, <replacement-expression-if-null> ] }

The arguments can be any valid expression. 参数可以是任何有效的表达式For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Example示例

The following example use a inventory collection with the following documents:以下示例将inventory集合与以下文档一起使用:

{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 }
{ "_id" : 2, "item" : "abc2", description: null, qty: 200 }
{ "_id" : 3, "item" : "xyz1", qty: 250 }

The following operation uses the $ifNull expression to return either the non-null description field value or the string "Unspecified" if the description field is null or does not exist:如果description字段为null或不存在,则以下操作使用$ifNull表达式返回非nulldescription字段值或字符串"Unspecified"

db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            description: { $ifNull: [ "$description", "Unspecified" ] }
         }
      }
   ]
)

The operation returns the following results:操作返回以下结果:

{ "_id" : 1, "item" : "abc1", "description" : "product 1" }
{ "_id" : 2, "item" : "abc2", "description" : "Unspecified" }
{ "_id" : 3, "item" : "xyz1", "description" : "Unspecified" }