我收集的文件,
{
"_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中得到null而不是连接字符串。请帮忙!!提前谢谢。
答案 0 :(得分:7)
您可以在分组期间连接所需的值并推送到数组:
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"]}}
}
}]
)