如何使用过滤后的数组和过滤后的总和来聚合分组?

时间:2017-09-13 01:17:28

标签: node.js mongodb aggregation-framework

我试图了解这个聚合框架,我有点卡住,我会喜欢一些帮助。

所以我有一系列事件,简化并已经过滤了类似的事情:

{ creation: 54233, eventName: "elapsedTime", userId: 1, url: "/thing/53e245ca", data: { number: 5 } },
{ creation: 64033, eventName: "elapsedTime", userId: 1, url: "/thing/53e245ca", data: { number: 3 } },
{ creation: 50298, eventName: "elapsedTime", userId: 1, url: "/thing/53e245ca", data: { number: 2 } },
{ creation: 74220, eventName: "toggle",      userId: 1, url: "/thing/53e245ca", data: { status: true } },
{ creation: 84233, eventName: "elapsedTime", userId: 2, url: "/thing/190345a9", data: { number: 8 } },
{ creation: 59511, eventName: "elapsedTime", userId: 2, url: "/thing/190345a9", data: { number: 10 } },
{ creation: 14236, eventName: "toggle",      userId: 2, url: "/thing/190345a9", data: { status: false } },
{ creation: 80637, eventName: "toggle",      userId: 2, url: "/thing/cc2b8b91", data: { status: true } },
{ creation: 99239, eventName: "toggle",      userId: 2, url: "/thing/cc2b8b91", data: { status: false } }

我希望他们像这样汇总:

{
    userId: 1,
    toggles: [
        { creation: 74220, url: "/thing/53e245ca", data: { status: true } }
    ],
    elapsedSum: 10
},
{
    userId: 2,
    toggles: [
        { creation: 14236, url: "/thing/190345a9", data: { status: false } },
        { creation: 80637, url: "/thing/cc2b8b91", data: { status: true } },
        { creation: 99239, url: "/thing/cc2b8b91", data: { status: false } },
    ],
    elapsedSum: 18
}

所以我基本上希望按用户分组,为每个用户提供所有elapsedTime的总和,并为每个用户提供所有toggle事件的数组。

1 个答案:

答案 0 :(得分:1)

db.getCollection('heya').aggregate([
  {
    "$group": {
      "_id": "$userId",
      "toogles": {
        "$addToSet": {
          "$cond": {
            "if": {
              "$eq": [
                "$eventName",
                "toggle"
              ]
            },
            "then": {
              "creation": "$creation",
              "url": "$url",
              "data": "$data"
            },
            "else": null
          }
        }
      },
      "elapsedSum": {
        "$sum": {
          "$cond": {
            "if": {
              "$eq": [
                "$eventName",
                "elapsedTime"
              ]
            },
            "then": "$data.number",
            "else": 0
          }
        }
      }
    }
  }
])

您可以从数组中替换null或展开它以获得所需的结果