$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, 在MongoDB 4.4及更早版本中,$ifNull
only accepts a single input expression:$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 ifdescription
is 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
返回:
如果description
if it is non-null.description
不是null
则为description
。如果quantity
ifdescription
is null or missing andquantity
is non-null.description
为空或缺失,并且quantity
为非空,则为quantity
。如果"Unspecified"
string ifdescription
andquantity
are 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" }