如何在 mongodb 的数组中合并具有相同键的对象?

How can I merge objects with the same key in an array in mongodb?

我使用 mongodb 的聚合得出以下数据。

{
    "first_count": 2,
    "second_count": 1,
    "third_count": 2,
    "test_count": 2,
    "sido": "대구",
    "guguns": [
        {
            "gugun": "남시",
            "first_count": 1,
            "second_count": 1,
            "third_count": 1
        },
        {
            "gugun": "부천군",
            "first_count": 1,
            "second_count": 0,
            "third_count": 1
        },
        {
            "gugun": "남시",
            "test_count": 1
        },
        {
            "gugun": "부천군",
            "test_count": 1
        }
    ]
}

这是合并两个方面数据的结果。但是我想要的结果是:

{
    "first_count": 2,
    "second_count": 1,
    "third_count": 2,
    "test_count": 2,
    "sido": "대구",
    "guguns": [
        {
            "gugun": "남시",
            "first_count": 1,
            "second_count": 1,
            "third_count": 1,
            "test_count": 1
        },
        {
            "gugun": "부천군",
            "first_count": 1,
            "second_count": 0,
            "third_count": 1,
            "test_count": 1
        }
    ]
}

guguns.gugun如何将相同的值合并为一个? 如果可能的话,我想使用 mongodb 聚合来处理它。

  • $unwind解构guguns数组
  • $mergeObjectsguguns 的当前对象与其他
  • 合并
  • $group 通过 _idguguns.gugun 属性 并获取必填字段第一个值和 guguns 合并对象
  • $group 仅通过 _id 并获取所需字段的第一个值并构造 guguns 对象的数组
db.collection.aggregate([
  { $unwind: "$guguns" },
  {
    $group: {
      _id: {
        _id: "$_id",
        gugun: "$guguns.gugun"
      },
      first_count: { $first: "$first_count" },
      second_count: { $first: "$second_count" },
      third_count: { $first: "$third_count" },
      test_count: { $first: "$test_count" },
      sido: { $first: "$sido" },
      guguns: { $mergeObjects: "$guguns" }
    }
  },
  {
    $group: {
      _id: "$_id._id",
      first_count: { $first: "$first_count" },
      second_count: { $first: "$second_count" },
      third_count: { $first: "$third_count" },
      test_count: { $first: "$test_count" },
      sido: { $first: "$sido" },
      guguns: { $push: "$guguns" }
    }
  }
])

Playground