Docs HomeMongoDB Manual

$ifNull (aggregation)

On this page本页内容

Definition定义

$ifNull

Changed in version 5.0.5.0版更改。

The $ifNull expression evaluates input expressions for null values and returns:$ifNull表达式计算输入表达式的null值,并返回:

  • The first non-null input expression value found.找到的第一个非null输入表达式值。
  • A replacement expression value if all input expressions evaluate to null.如果所有输入表达式的计算结果均为null,则为替换表达式值。

$ifNull treats undefined values and missing fields as null.将未定义的值和缺少的字段视为null

Syntax:语法:

{
$ifNull: [
<input-expression-1>,
...
<input-expression-n>,
<replacement-expression-if-null>
]
}

In MongoDB 4.4 and earlier versions, $ifNull only accepts a single input expression:在MongoDB 4.4及更早版本中,$ifNull只接受单个输入表达式:

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

Examples实例

This inventory collection is used in the examples: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" }
] )

Single Input Expression单个输入表达式

The following example uses $ifNull to return:以下示例使用$ifNull返回:

  • description if it is non-null.如果description不是null则为description
  • "Unspecified" string if description is null or missing.如果descriptionnull或缺失,则为"Unspecified"字符串。
db.inventory.aggregate(
[
{
$project: {
item: 1,
description: { $ifNull: [ "$description", "Unspecified" ] }
}
}
]
)

Output:输出:

{ "_id" : 1, "item" : "buggy", "description" : "toy car" }
{ "_id" : 2, "item" : "bicycle", "description" : "Unspecified" }
{ "_id" : 3, "item" : "flag", "description" : "Unspecified" }

Multiple Input Expressions多个输入表达式

New in version 5.0. 5.0版新增。

The following example uses $ifNull to return:以下示例使用$ifNull返回:

  • description if it is non-null.如果description不是null则为description
  • quantity if description is null or missing and quantity is non-null.如果description为空或缺失,并且quantity为非空,则为quantity
  • "Unspecified" string if description and quantity are both null or missing.如果descriptionquantity均为null或缺失,则为"Unspecified"字符串。
db.inventory.aggregate(
[
{
$project: {
item: 1,
value: { $ifNull: [ "$description", "$quantity", "Unspecified" ] }
}
}
]
)

Output:输出:

{ "_id" : 1, "item" : "buggy", "value" : "toy car" }
{ "_id" : 2, "item" : "bicycle", "value" : 200 }
{ "_id" : 3, "item" : "flag", "value" : "Unspecified" }