Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs 菜单
Docs 主页
/ /

$ifNull(表达式操作符)

$ifNull

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

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

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

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

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

{
$ifNull: [
<input-expression-1>,
...
<input-expression-n>,
<replacement-expression-if-null>
]
}

本页上的示例使用 sample_mflix示例数据集 中的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载示例数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。

以下示例使用 $ifNull 返回:

  • rated 如果 rated字段非空。

  • "Not Rated" 字段符(如果 rated 为 null 或缺失)。

db.movies.aggregate(
[
{ $match: { year: { $lt: 1910 } } },
{
$project: {
_id: 0,
title: 1,
rated: { $ifNull: [ "$rated", "Not Rated" ] }
}
},
{ $sort: { title: 1 } }
]
)
[
{ title: 'A Corner in Wheat', rated: 'G' },
{ title: 'The Great Train Robbery', rated: 'TV-G' },
{ title: 'The Kiss', rated: 'Not Rated' },
{ title: 'The Kiss', rated: 'Not Rated' }
]

版本 5.0 中的新增功能

以下示例使用 $ifNull 返回:

  • tomatoes.critic.rating 如果它不为空。

  • tomatoes.viewer.rating 如果 tomatoes.critic.rating 为空或缺失,而 tomatoes.viewer.rating 为非空。

  • 0 如果 tomatoes.critic.ratingtomatoes.viewer.rating 均为 null 或缺失。

db.movies.aggregate(
[
{ $match: { year: { $lt: 1910 } } },
{
$project: {
_id: 0,
title: 1,
rating: { $ifNull: [ "$tomatoes.critic.rating", "$tomatoes.viewer.rating", 0 ] }
}
},
{ $sort: { title: 1 } }
]
)
[
{ title: 'A Corner in Wheat', rating: 3.6 },
{ title: 'The Great Train Robbery', rating: 7.6 },
{ title: 'The Kiss', rating: 4 },
{ title: 'The Kiss', rating: 0 }
]

后退

$hour

在此页面上