$ifNull (聚合)
定义
变更版本5.0.
的$ifNull
表达式评估输入表达式以查找null值,并返回
第一个非null的输入表达式值。
如果所有输入表达式都评估为null,则返回
$ifNull
将未定义的值和缺失的字段视为null。
兼容性
您可以使用$ifNull
在以下环境中部署
MongoDB Atlas:云中MongoDB部署的全托管服务
MongoDB Enterprise:基于订阅的自托管MongoDB版本
MongoDB Community:源代码可用、免费使用和自托管MongoDB版本
语法
{ $ifNull: [ <input-expression-1>, ... <input-expression-n>, <replacement-expression-if-null> ] }
示例
本示例中使用此 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" } ] )
单个输入表达式
以下示例使用 $ifNull
返回
description
如果它非空。"Unspecified"
字符串如果description
为空或不存在。
db.inventory.aggregate( [ { $project: { item: 1, description: { $ifNull: [ "$description", "Unspecified" ] } } } ] )
输出
{ "_id" : 1, "item" : "buggy", "description" : "toy car" } { "_id" : 2, "item" : "bicycle", "description" : "Unspecified" } { "_id" : 3, "item" : "flag", "description" : "Unspecified" }
多个输入表达式
新版本5.0.
以下示例使用 $ifNull
返回
description
如果它非空。如果
数量
为空或不存在且数量
非空。如果
描述
和数量
均为空或不存在,则为 "未指定" 字符串。
db.inventory.aggregate( [ { $project: { item: 1, value: { $ifNull: [ "$description", "$quantity", "Unspecified" ] } } } ] )
输出
{ "_id" : 1, "item" : "buggy", "value" : "toy car" } { "_id" : 2, "item" : "bicycle", "value" : 200 } { "_id" : 3, "item" : "flag", "value" : "Unspecified" }