xx *_* yy 3 mongodb mongodb-query aggregation-framework
我想通过聚合管道中的投影阶段修改一个字段,该字段是由(-)分隔的其他字段值的组合
如果该字段为空或为空或缺失,则不会将其添加到串联字符串中
{$project:{
//trial-1:
finalField:{
$concat["$field1",'-','$field2','-','$field3',...]
//problem1: $concat will return null if any of it's arguments is null or missing
//problem2: if all the fields are exist with non-null values, the delimiter will exists even if the field dosen't
}
//trial-2:
finalField:{
$concat:[
{$cond:[{field1:null},'',{$concat:['$field1','-']},..]
//the problem: {field1:null} fails if the field dosen't exixt (i.e the expression gives true)
//trial-3
finalField:{
$concat:[
{$cond:[{$or:[{field1:null},{field:{$exists:true}},'',
{$concat:['$field1','-']}
]}]}
]
}
]
}
//trial-4 -> using $reduce instead of $concate (same issues)
Run Code Online (Sandbox Code Playgroud)
}
Nei*_*unn 11
你基本上想要$ifNull. 它“有点”像$exists聚合语句,当字段表达式返回时,它返回一个默认值null,意思是“不存在”:
{ "$project": {
"finalField": {
"$concat": [
{ "$ifNull": [ "$field1", "" ] },
"-",
{ "$ifNull": [ "$field2", "" ] },
"-",
{ "$ifNull": [ "$field3", "" ] }
]
}
}}
Run Code Online (Sandbox Code Playgroud)
例如,数据如下:
{ "field1": "a", "field2": "b", "field3": "c" },
{ "field1": "a", "field2": "b" },
{ "field1": "a", "field3": "c" }
Run Code Online (Sandbox Code Playgroud)
当然,您会得到,不会产生任何错误:
{ "finalField" : "a-b-c" }
{ "finalField" : "a-b-" }
{ "finalField" : "a--c" }
Run Code Online (Sandbox Code Playgroud)
如果您想要更奇特的东西,那么您可以动态地使用名称,如下所示:
{ "$project": {
"finalField": {
"$reduce": {
"input": {
"$filter": {
"input": { "$objectToArray": "$$ROOT" },
"cond": { "$ne": [ "$$this.k", "_id" ] }
}
},
"initialValue": "",
"in": {
"$cond": {
"if": { "$eq": [ "$$value", "" ] },
"then": { "$concat": [ "$$value", "$$this.v" ] },
"else": { "$concat": [ "$$value", "-", "$$this.v" ] }
}
}
}
}
}}
Run Code Online (Sandbox Code Playgroud)
它可以知道实际存在哪些字段,并且只尝试加入这些字段:
{ "finalField" : "a-b-c" }
{ "finalField" : "a-b" }
{ "finalField" : "a-c" }
Run Code Online (Sandbox Code Playgroud)
如果您不想覆盖$objectToArray文档或子文档,您甚至可以手动指定字段列表:
{ "$project": {
"finalField": {
"$reduce": {
"input": {
"$filter": {
"input": ["$field1", "$field2", "$field3"],
"cond": { "$ne": [ "$$this", null ] }
}
},
"initialValue": "",
"in": {
"$cond": {
"if": { "$eq": [ "$$value", "" ] },
"then": { "$concat": [ "$$value", "$$this" ] },
"else": { "$concat": [ "$$value", "-", "$$this" ] }
}
}
}
}
}}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3305 次 |
| 最近记录: |