简体   繁体   English

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

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

I derived the following data using the aggregate of 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
        }
    ]
}

This is the result of merging two facet data.这是合并两个方面数据的结果。 But the result I want is:但我想要的结果是:

{
    "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
        }
    ]
}

How does guguns.gugun combine the same values into one? guguns.gugun如何将相同的值合并为一个? If possible, I would like to process it using mongodb aggregate.如果可能的话,我想使用 mongodb 聚合来处理它。

  • $unwind deconstruct the guguns array $unwind解构guguns数组
  • $mergeObjects to merge current object of guguns with other $mergeObjects合并的当前对象guguns与其他
  • $group by _id and guguns.gugun property and get required fields first value and guguns merged object $group by _idguguns.gugun属性并获取必填字段第一个值和guguns合并对象
  • $group by only _id and get required fields first value and construct the array of guguns object $group by only _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操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM