Mongodb集合中对文档结构没有严格限制。随着业务的变化,字段也会出现新增,修改等操作。当读取新字段时,旧数据因为不存在该字段而返回空数据。
mongodb的聚合操作符中的$ifNull,按照用户指定的方式返回空字段值,为字段缺失查询提供了便利和灵活性。
功能
$ifNull,逐一判断传入表达式数组元素的值,如果当前表达式为空值,则获取下一个表达式的值。依次向下传递,直到获取到$ifNull表达式中用户传递的默认值。表达式返回值中,undefined和字段缺失,都会被认为是空值。
语法
在下面表达式中,用户在$ifNull参数数组中可以指定一个或多个输入表达式。$ifNull返回第一个值不为空表达式的结果。如input-expression-1的值为空,判断input-expression-2的值,当input-expression-2的值不为空时,返回input-expression-2的值,否则继续向下判断input-expression-3.直到所有表达式为空时,返回<replacement-expression-if-null>的值
{
$ifNull: [
<input-expression-1>,...
<input-expression-n>,<replacement-expression-if-null>
]
}
在Mongodb 4.4版本以前的$ifNull参数,只接受用户输入一个表达式。
{
$ifNull: [
<input-expression-1>,<replacement-expression-if-null>
]
}
应用举例
构建测试集inventory,其中{"_id":2}的文档中,description字段为空值,而{"_id":3}的文档不存在description和quantity字段
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"
db.inventory.aggregate([
{
$project: {
item: 1,description: {
$ifNull: ["$description","Unspecified"]
}
}
}
])
$ifNull中多个表达式
当description字段为空时,返回字段quantity的值。而当quantity也为空时,返回"Unspecified"
db.inventory.aggregate([
{
$project: {
item: 1,"$quantity","Unspecified"]
}
}
}
])
其中{"_id":2}的文档中,description字段为空,返回quantity字段中的200,而{"_id":3}的文档不存在description和quantity字段,返回"Unspecified"
原文地址:https://blog.csdn.net/wilsonzane/article/details/135476354
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。