$ifNull用于判断第一个表达式是否为 NULL,如果为 NULL 则返回第二个参数的值,如果不为 NULL 则返回第一个参数的值。
$ifNull表达式格式为:
{ $ifNull: [ <expression>, <replacement-expression-if-null> ] }
例子:
原始数据:
{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 }
{ "_id" : 2, "item" : "abc2", description: null, qty: 200 }
{ "_id" : 3, "item" : "xyz1", qty: 250 }
处理语句:
db.inventory.aggregate(
[
{
$project: {
item: 1,
description: { $ifNull: [ "$description", "Unspecified" ] }
}
}
]
)
结果:
{ "_id" : 1, "item" : "abc1", "description" : "product 1" }
{ "_id" : 2, "item" : "abc2", "description" : "Unspecified" }
{ "_id" : 3, "item" : "xyz1", "description" : "Unspecified" }
本文详细介绍了MongoDB中$ifNull操作符的使用方法,该操作符用于判断表达式是否为NULL,若为NULL则返回指定替代值。通过实例展示了如何在聚合管道中使用$ifNull来处理字段缺失的情况,确保数据一致性。
815

被折叠的 条评论
为什么被折叠?



