gpt4 book ai didi

mongodb - 当并非所有字段都有值时加入字段

转载 作者:行者123 更新时间:2023-12-05 01:16:30 25 4
gpt4 key购买 nike

我想通过聚合管道中的投影阶段修改一个字段,这个字段是由(-)分隔的其他字段值的组合

如果该字段为 null 或为空或缺失,则不会将其添加到串联字符串中

{$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)

最佳答案

你基本上想要 $ifNull . “有点” 就像 $exists但是对于聚合语句,当字段表达式返回 null 时,它返回一个默认值,意思是“不存在”:

{ "$project": {
"finalField": {
"$concat": [
{ "$ifNull": [ "$field1", "" ] },
"-",
{ "$ifNull": [ "$field2", "" ] },
"-",
{ "$ifNull": [ "$field3", "" ] }
]
}
}}

例如数据如下:

{ "field1": "a", "field2": "b", "field3": "c" },
{ "field1": "a", "field2": "b" },
{ "field1": "a", "field3": "c" }

你得到了,当然不会产生任何错误:

{ "finalField" : "a-b-c" }
{ "finalField" : "a-b-" }
{ "finalField" : "a--c" }

如果您想要更花哨的东西,那么您将改为动态使用名称,如下所示:

  { "$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" ] }
}
}
}
}
}}

哪些可以知道实际存在哪些字段并仅尝试加入这些字段:

{ "finalField" : "a-b-c" }
{ "finalField" : "a-b" }
{ "finalField" : "a-c" }

如果您不希望 $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" ] }
}
}
}
}
}}

关于mongodb - 当并非所有字段都有值时加入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com