文档菜单
文档首页
/
MongoDB 手册
/ / /

$ifNull (聚合)

本页

  • 定义
  • 兼容性
  • 语法
  • 示例
$ifNull

变更版本5.0.

$ifNull表达式评估输入表达式以查找null值,并返回

  • 第一个非null的输入表达式值。

  • 如果所有输入表达式都评估为null,则返回

$ifNull将未定义的值和缺失的字段视为null。

您可以使用$ifNull在以下环境中部署

{
$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" }

返回

小时