定义
$ifNull 表达式计算输入表达式的 null 值并返回:
$ifNull 将未定义的值和缺失字段视为 null。
兼容性
可以使用 $ifNull 查找托管在以下环境中的部署:
MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
{ $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.rating和tomatoes.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 } ]