【问题标题】:Aggregate occurrences of events in nested array聚合嵌套数组中事件的出现
【发布时间】:2022-12-13 20:09:03
【问题描述】:

给定以下输入:

[
  {
    "statuses": [
      {
        "status": "allowed",
        "count": 3,
        "events_count": [
          "2001",
          "1001",
          "1001"
        ]
      }
    ],
    "date": "2022-09-10 15:00",
    "_id": "2022-09-10 15:00"
  }
]

我需要计算 stauses.events_count 的出现次数,因此输出将是:

[
  {
    "statuses": [
      {
        "status": "allowed",
        "count": 3,
        "events_count": [
          {"type": "2001", "count": 1},
          {"type": "1001", "count": 2},
        ]
      }
    ],
    "date": "2022-09-10 15:00",
    "_id": "2022-09-10 15:00"
  }
]

我试过的

这是我到目前为止得到的:

db.collection.aggregate([
  {
    "$unwind": "$statuses"
  },
  {
    "$unwind": "$statuses.events_count"
  },
  {
    "$group": {
      "_id": {
        "event_count": "$statuses.events_count",
        "status": "$statuses.status",
        "date": "$date",
        "count": "$statuses.count"
      },
      "occurences": {
        "$sum": 1
      }
    }
  }
])

哪个产生:

[
  {
    "_id": {
      "count": 3,
      "date": "2022-09-10 15:00",
      "event_count": "2001",
      "status": "allowed"
    },
    "occurences": 1
  },
  {
    "_id": {
      "count": 3,
      "date": "2022-09-10 15:00",
      "event_count": "1001",
      "status": "allowed"
    },
    "occurences": 2
  }
]

我很难将所有内容重新组合在一起。我尝试按日期分组并推回到“statuses”数组,但它在数组中生成两个项目(status==allowed),而不是 status==allowed 的 1 个项目

【问题讨论】:

标签: mongodb aggregation-framework


【解决方案1】:

你做了 2 个 $unwinds,所以它应该是 2 个 $groups 相反的顺序:

  {
    "$group": {
      "_id": {
        "status": "$_id.status",
        "count": "$_id.count",
        "date": "$_id.date"
      },
      "event_count": {
        "$push": {
          "type": "$_id.event_count",
          "count": "$occurences"
        }
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.date",
      "date": {"$last": "$_id.date"},
      "statuses": {
        "$push": {
          "status": "$_id.status",
          "count": "$_id.count",
          "event_count": "$event_count"
        }
      }
    }
  }

【讨论】:

    猜你喜欢
    • 2017-07-26
    • 2015-12-06
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    相关资源
    最近更新 更多