“文档” 菜单
文档首页
/
MongoDB Manual
/ / /

$ifNull(聚合)

在此页面上

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

5.0 版本中的更改

$ifNull 表达式计算输入表达式的 null 值并返回:

  • 找到第一个非空输入表达式值。

  • 如果所有输入表达式均为空,则替换表达式值。

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

可以使用 $ifNull 查找托管在以下环境中的部署:

  • MongoDB Atlas :用于在云中部署 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 为 null 或缺失)。

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 如果非空。

  • quantity 如果 description 为空或缺失,而 quantity 为非空。

  • "Unspecified" 字符串(如果 descriptionquantity 都为 null 或缺失)。

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" }
← $hour(聚合)