【问题标题】:MongoDB 4.2 Multiple Grouping for Nested resultsMongoDB 4.2 嵌套结果的多重分组
【发布时间】:2020-01-31 22:04:23
【问题描述】:

我正在尝试根据以下数据编写嵌套组查询:

[
    {
        "mmyy": "JAN-2019",
        "location": "Boston",
        "category": "Shoes",
        "qty": 5
    },
    {
        "mmyy": "JAN-2019",
        "location": "New York",
        "category": "Shoes",
        "qty": 10
    },
    {
        "mmyy": "JAN-2019",
        "location": "Boston",
        "category": "Hats",
        "qty": 2
    },
    {
        "mmyy": "JAN-2019",
        "location": "New York",
        "category": "Hats",
        "qty": 3
    },
    {
        "mmyy": "FEB-2019",
        "location": "Boston",
        "category": "Shoes",
        "qty": 5
    },
    {
        "mmyy": "FEB-2019",
        "location": "New York",
        "category": "Hats",
        "qty": 10
    },
]

想要的结果:

[
  {
    month: "JAN-2019",
    month_total: 20,
    locations:[
       { 
          name: "Boston", 
          location_total: 7,
          categories: [
            {name: "Shoes", total: 5},
            {name: "Hats", total: 2},
          ]
       }
      ...
    ]
  },
  ...
]

我能够达到第二级聚合(对于月份和位置),但是很难将所有聚合归结为嵌套结果中的类别。这就是我所做的,使用多个$group$push

db.sales.aggregate([
   {$group: {
      _id:{ month: "$mmyy", location: "$location"},
      total: { $sum: "$qty"} 
   }},
   { $group:{
      _id: "$_id.month", 
      monthly_total: { $sum: "$total" },
      locations: {
         $push:{
           name: "$_id.location",
           total: "$total"
         }
      }
   }}
])

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework grouping


    【解决方案1】:

    您需要在第一个$group 阶段$push categories

    db.collection.aggregate([
      { "$group": {
        "_id": {
          "month": "$mmyy",
          "location": "$location",
          "category": "$category"
        },
        "total": { "$sum": "$qty" }
      }},
      { "$group": {
        "_id": {
          "month": "$_id.month",
          "location": "$_id.location"
        },
        "categories": {
          "$push": {
            "name": "$_id.category",
            "total": "$total"
          }
        }
      }},
      { "$group": {
        "_id": "$_id.month",
        "locations": {
          "$push": {
            "name": "$_id.location",
            "categories": "$categories",
            "location_total": {
              "$sum": "$categories.total"
            }
          }
        }
      }}
    ])
    

    【讨论】:

    • 实际上,当我这样做时似乎有一种奇怪的行为。在每个“位置”下,我得到一个重复“类别”的列表,其中同一类别出现多次,total 在它们之间拆分。
    • 当然。如果您在任何月份为某个位置的每个“类别”有多个条目,就会发生这种情况。看这里:https://mongoplayground.net/p/J7sIWG5i0My
    猜你喜欢
    • 1970-01-01
    • 2019-11-25
    • 2021-03-19
    • 2018-05-16
    • 1970-01-01
    • 2021-12-02
    • 2021-12-16
    • 1970-01-01
    • 2021-04-19
    相关资源
    最近更新 更多