来自以下文档示例:
{
"_id" : ObjectId("528e4798bfa9782c078b4662"),
"query" : {
"start-date" : ISODate("2013-11-19T00:00:00Z"),
"end-date" : ISODate("2013-11-20T00:00:00Z"),
"ids" : "ga:69564270",
"dimensions" : "ga:visitorType,ga:visitCount",
"metrics" : [
"ga:organicSearches"
]
},
"columnHeaders" : [
{
"name" : "ga:visitorType",
"columnType" : "DIMENSION",
"dataType" : "STRING"
},
{
"name" : "ga:visitCount",
"columnType" : "DIMENSION",
"dataType" : "STRING"
},
{
"name" : "ga:organicSearches",
"columnType" : "METRIC",
"dataType" : "INTEGER"
}
],
"totalsForAllResults" : {
"ga:organicSearches" : 119
},
"rows" : [
[
"New Visitor",
"1",
100
],
[
"Returning Visitor",
"11",
1
],
[
"Returning Visitor",
"2",
10
],
[
"New Visitor",
"3",
4
],
[
"Returning Visitor",
"4",
1
],
[
"Returning Visitor",
"5",
1
],
[
"New Visitor",
"6",
1
],
[
"New Visitor",
"8",
1
]
],
"query_name" : "GA Organic Traffic Metric",
"profile_id" : 666,
"retrieve_date" : ISODate("2013-11-21T17:49:12Z")
}
我如何使用mongo聚合框架:
目前,正如你可以看到“ga:organicSearches”我有两者的总和,但我需要各自类型的访问者,例如“ga:organicSearchesReturningVisitors”和“ga:organicSearchesNewVisitors”。
提前致谢。
答案 0 :(得分:0)
只要您可以进行两次聚合,就可以这样做(我假设每个文档代表一天):
新访客:
db.visitors.aggregate({$unwind:"$rows"},
{$match:{"rows.0":"New Visitor"}},
{$unwind:"$rows"},
{$match:{"rows":{$type:1}}},
{$group:{_id:"$query.start-date",newVisitorsSum:{$sum:"$rows"}}});
{ "_id" : ISODate("2013-11-19T00:00:00Z"), "newVisitorsSum" : 106 }
回访者:
db.visitors.aggregate({$unwind:"$rows"},
{$match:{"rows.0":"Returning Visitor"}},
{$unwind:"$rows"},
{$match:{"rows":{$type:1}}},
{$group:{_id:"$query.start-date",retVisitorsSum:{$sum:"$rows"}}});
{ "_id" : ISODate("2013-11-19T00:00:00Z"), "retVisitorsSum" : 13 }