【问题标题】:MongoDB nested array aggregationMongoDB 嵌套数组聚合
【发布时间】:2018-08-22 19:04:33
【问题描述】:

我想为以下示例数组聚合数据。

 [
  {
    "_id": "5b7c0540342100091a375793",
    "pages": [
      {
        "name": "ABCD",
        "sections": [
          {
            "name": "sectionThird",
            "id": 2,
            "value": [
              10,
              50,
              20
            ]
          }
        ]
      }
    ]
  },
  {
    "_id": "5b3cd546342100514b4683a2",
    "pages": [
      {
        "name": "ABCD",
        "sections": [
          {
            "name": "sectionFourth",
            "id": 2,
            "value": [
              19,
              5,
              8
            ]
          },
          {
            "name": "sectionThird",
            "id": 2,
            "value": [
              60
            ]
          }
        ]
      },
      {
        "name": "EFGH",
        "sections": [
          {
            "name": "sectionFourth",
            "id": 2,
            "value": [
              5
            ]
          },
          {
            "name": "sectionThsads",
            "id": 2,
            "value": [
              8
            ]
          }
        ]
      }
    ]
  }
]

我想要以下输出:

 [
  {
    "page": "ABCD",
    "sections": [
      {
        "name": "sectionThird",
        "totalValue": 140
      },
      {
        "name": "sectionFourth",
        "totalValue": 32
      }
    ]
  },
  {
    "page": "EFGH",
    "sections": [
      {
        "name": "sectionFourth",
        "totalValue": 5
      },
      {
        "name": "sectionThsads",
        "totalValue": 8
      }
    ]
  }
]

在上面的示例数组中,您可以看到有多个以“page”作为键之一的文档,它们也是一个对象数组。每个页面对象都有一个键“名称”,这对于“页面”数组中的每个对象都是唯一的。 “page”对象有“sections”键,它们也有“name”键,每个对象都是唯一的。

因此,输出数组按 page.name 分组,然后按sections.name 分组,来自所有页面对象,并且具有相同节名的页面对象内的所有节中的所有值数组的总和。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您可以使用以下聚合。

    $unwind 每个页面和部分后跟 $group$sum 对每个部分的值求和,$push 将部分值推回页面数组。

    db.col.aggregate([
    {"$unwind":"$pages"},
    {"$unwind":"$pages.sections"},
    {"$group":{
      "_id":{"pagename":"$pages.name","sectionname":"$pages.sections.name"},
      "totalTime":{"$sum":{"$sum":"$pages.sections.value"}}
    }},
    {"$group":{
      "_id":"$_id.pagename",
      "sections":{"$push":{"name":"$_id.sectionname","totalTime":"$totalTime"}}
    }}])
    

    【讨论】:

    • 谢谢。像魅力一样工作。
    猜你喜欢
    • 2017-07-26
    • 2017-07-16
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2023-01-13
    • 2021-06-27
    • 2015-12-06
    • 1970-01-01
    相关资源
    最近更新 更多