密钥上的mongo db聚合

时间:2019-03-21 11:51:16

标签: mongodb aggregation-framework

我正碰壁,试图汇总和汇总一些文档。

具有类似文档:

Doc1

{
  "_id": ObjectId("5c936353a27248985d4a23a8"),
  "aid": "XXX",
  "day": NumberLong(1553126400),
  "channels": {
    "desktop": {
      "page1": {
        "hits": 2
      },
      "page2": {
        "hits": 2
      }
    },
    "mobile": {
      "page1": {
        "hits": 4
      }
      "page2": {
        "hits": 4
      }
    }
  }
}

Doc2

{
  "_id": ObjectId("5c936353a27248985d4a23a7"),
  "aid": "XXX",
  "day": NumberLong(1553116400),
  "channels": {
    "desktop": {
      "page1": {
        "hits": 4
      },
      "page2": {
        "hits": 6
      }
    },
    "mobile": {
      "page1": {
        "hits": 8
      }
      "page2": {
        "hits": 8
      }
    }
  }
}

我想运行一条管道,以总计特定页面和家庭的所有“匹配”

我想要的结果是:

{
  "_id": "XX",
  "channels": {
    "desktop": {
       "page1": {
          "hits": 6
       },
       "page2": {
          "hits": 8
       }
     },
    "mobile": {
       "page1": {
             "hits": 12
            },
       "page2": {
             "hits": 12
             }
     }
  }
}

在这种情况下,我无法找到如何进行$sum的样本。

1 个答案:

答案 0 :(得分:0)

我想出了:

[
    {
        "$match": {
            "aid": "5c90b9c936636572bb83fe93",
            "day": 
                { 
                    "$gte": 1550575794, 
                    "$lte": 1553126400 
                }
        }
    },
    {
        $project:
            {
                "o":
                    {
                    $objectToArray: "$channels"
                 }
            }
    },
    {
        $unwind: "$o"
    },
    {
        $project: {
         "family": "$o.k",
         "p": {
            $objectToArray: "$o.v"
            }
        }
    },
    {
        $unwind: "$p"
    }
    ,
    {
        $group: {
            "_id": {"path": "$p.k", family: "$family"},
            "sum": {$sum: "$p.v.hits"}

        }
    }



]

产生类似这样的文档:

enter image description here