定义
The $ifNull expression evaluates input expressions for null values and returns:
$ifNull 将未定义的值和缺失字段视为 null。
兼容性
可以使用 $ifNull 查找托管在以下环境中的部署:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
{ $ifNull: [ <input-expression-1>, ... <input-expression-n>, <replacement-expression-if-null> ] }
示例
本页上的示例使用来自 sample_mflix 数据集的数据。有关如何将此数据集加载到您的自管理 MongoDB 部署中的详细信息,请参阅 加载示例数据集。如果您对示例数据库进行了任何修改,您可能需要删除并重新创建数据库,才能运行此页面上的示例。
单个输入表达式
The following example uses $ifNull to return:
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 中的新增功能。
The following example uses $ifNull to return:
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 } ]