我在 MongoDB 中有如下所示的分析文档:
{
"_id" : ObjectId("id1"),
"userObjectId" : "abc",
"eventType" : "First Signup",
"date" : ISODate("2017-09-10T20:46:42.144Z")
}
{
"_id" : ObjectId("id2"),
"userObjectId" : "abc",
"eventType" : "First Launch",
"date" : ISODate("2017-09-10T20:46:31.291Z")
}
现在我构建了一个查询来按日期和事件类型对结果进行分组:
{
"collection": "Analytics",
"aggregate": [
{
"$project": {
"yearMonthDay": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": "$date"
}
},
"date": 1,
"userObjectId": 1,
"_id": 1,
"eventType": 1
}
},
{
"$group": {
"_id": { "ymd": "$yearMonthDay", "event": "$eventType" },
"num_in_group_count": {
"$sum": 1
},
"date": { "$last": "$yearMonthDay" },
"event": { "$last": "$eventType" }
}
}
]
}
这确实按日期和类型生成数据,如下所示:
{
"_id" : {
"ymd" : "2017-09-10",
"event" : "First Signup"
},
"num_in_group_count" : 2.0,
"date" : "2017-09-10",
"event" : "First Signup"
}
{
"_id" : {
"ymd" : "2017-09-10",
"event" : "First End Onboarding"
},
"num_in_group_count" : 1.0,
"date" : "2017-09-10",
"event" : "First Launch"
}
但是我想在 Redash 中绘制它,所以真的希望将事件结构化的数据更改为如下所示的键:
{
"_id" : "2017-09-10",
"First Signup" : 2.0,
"First Launch" : 1.0,
"date" : "2017-09-12"
}
我怎样才能实现这个查询?