Database Manual / Reference / Query Language / Expressions

$ifNull (expression operator)(表达式运算符)

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.找到第一个非空输入表达式值。
  • A replacement expression value if all input expressions evaluate to null.如果所有输入表达式的计算结果都为null,则返回替换表达式值。

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

Compatibility兼容性

You can use $ifNull for deployments hosted in the following environments:您可以将$ifNull用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

{
$ifNull: [
<input-expression-1>,
...
<input-expression-n>,
<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.如果descriptionnull并且quantity不为null,则为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" }