gpt4 book ai didi

mongodb - 聚合中 mongodb 中字段的组连接

转载 作者:可可西里 更新时间:2023-11-01 09:57:12 25 4
gpt4 key购买 nike

我收藏的文档,

{
"_id" : "abc1",
"Data" : {
"Campaign Name" : "Campaign 1",
"Ad Set Name" : "Adset 1",
"Ad Name" : "Ad 1",
"URL Tags" : "url tag 1"
}
},
{
"_id" : "abc2",
"Data" : {
"Campaign Name" : "Campaign 2",
"Ad Set Name" : "Adset 1",
"Ad Name" : "Ad 1",
"URL Tags" : "url tag 1"
}
},
{
"_id" : "abc3",
"Data" : {
"Campaign Name" : "Campaign 2",
"Ad Set Name" : "Adset 2",
"Ad Name" : "Ad 2",
"URL Tags" : "url tag 2"
}
},
{
"_id" : "abc4",
"Data" : {
"Campaign Name" : "Campaign 3",
"Ad Set Name" : "Adset 1",
"Ad Name" : "Ad 1",
"URL Tags" : "url tag 1"
}
}

在输出中需要这样的东西,

{
"_id" : "Campaign 3",
"total" : 60.0,
"myField" : [ "url tag 1-Ad 1" ]
},
{
"_id" : "Campaign 2",
"total" : 120.0,
"myField" : [ "url tag 1-Ad 1", "url tag 2-Ad 2" ]
},
{
"_id" : "Campaign 1",
"total" : 96.0,
"myField" : [ "url tag 1-Ad 1" ]
}

到目前为止我做了什么(不成功的),

db.adsets.aggregate([
{$group:{_id:"$Data.Campaign Name",total:{$sum:1}}},
{$project:{_id:1,total:1,myField:{$concat:["$Data.URL Tags","-","$Data.Ad Name"]}}}
],{explain:false});

目前正在输出中,

{
"_id" : "Campaign 3",
"total" : 60.0,
"myField" : null
},
{
"_id" : "Campaign 2",
"total" : 120.0,
"myField" : null
},
{
"_id" : "Campaign 1",
"total" : 96.0,
"myField" : null
}

我不知道我做错了什么,这就是为什么我在 myField 中得到的是空值而不是串联字符串。请帮忙!!提前致谢。

最佳答案

您可以连接所需的值并在分组期间推送到数组:

db.adsets.aggregate([
{$group:{
_id:"$Data.Campaign Name",
total : {$sum:1},
myfield: {$push: {$concat:["$Data.URL Tags", "-", "$Data.Ad Name"]}}
}
}]
)

这应该会像您提到的那样给出输出。
(正如您在问题评论中提到的, myfield 字段将是您需要的数组,而不是像初始问题那样的对象)

如果你不希望连接的值在相同时出现两次,你可以使用 $addToSet 而不是 push

db.adsets.aggregate([
{$group:{
_id:"$Data.Campaign Name",
total : {$sum:1},
myfield: {$addToSet: {$concat:["$Data.URL Tags", "-", "$Data.Ad Name"]}}
}
}]
)

关于mongodb - 聚合中 mongodb 中字段的组连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42395406/

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