在MongoDB聚合查询中将值更改为键

时间:2017-09-13 00:24:04

标签: mongodb mongodb-query redash

我在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"
}

如何实现此查询?

1 个答案:

答案 0 :(得分:0)

你应该先按日期分组

然后使用此查询获取结果,请检查First Signup&的空值。登录

db.getCollection('heya').aggregate([
  {
    "$group": {
      "_id": "$date",
      "First Login": {
        "$sum": {
          "$cond": {
            "if": {
              "$eq": [
                "$eventType",
                "First Launch"
              ]
            },
            "then": 1,
            "else": 0
          }
        }
      },
      "First Signup": {
        "$sum": {
          "$cond": {
            "if": {
              "$eq": [
                "$eventType",
                "First Signup"
              ]
            },
            "then": 1,
            "else": 0
          }
        }
      },
      "date": {
        "$addToSet": "$date"
      }
    }
  },
  {
    "$unwind": "$date"
  }
]);