On this page本页内容
Changed in version 5.0.在版本5.0中更改。
The $ifNull
expression evaluates input expressions for null values and returns:$ifNull
表达式计算输入表达式的空值并返回:
$ifNull
treats undefined values and missing fields as 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> ] }
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" } ] )
The following example uses 以下示例使用$ifNull
to return:$ifNull
返回:
description
if it is non-null.description
非空,则为description
。"Unspecified"
string if description
is null or missing.description
为空或缺失,则为"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" }
New in version 5.0.在版本5.0中新增。
The following example uses 以下示例使用$ifNull
to return:$ifNull
返回:
description
if it is non-null.description
非空,则为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.description
和quantity
都是空或缺失,则为"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" }