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返回:
如果descriptionif it is non-null.description不是null则为description。如果"Unspecified"string ifdescriptionis null or missing.description为null或缺失,则为"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返回:
如果descriptionif it is non-null.description不是null,则为description如果quantityifdescriptionis null or missing andquantityis non-null.description是null并且quantity不为null,则为quantity如果"Unspecified"string ifdescriptionandquantityare both null or missing.description和quantity两者都是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" }