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

Posted

技术标签:

【中文标题】如何在 mongodb 的数组中合并具有相同键的对象?【英文标题】:How can I merge objects with the same key in an array in mongodb? 【发布时间】:2021-12-18 11:06:36 【问题描述】:

我使用 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 聚合来处理它。

【问题讨论】:

【参考方案1】: $unwind 解构 guguns 数组 $mergeObjectsguguns 的当前对象与其他对象合并 $group by _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

【讨论】:

以上是关于如何在 mongodb 的数组中合并具有相同键的对象?的主要内容,如果未能解决你的问题,请参考以下文章

如何合并具有相同键或不同键的多个字典?

如何解析具有相同键的不同数据类型的改造对象的json数组

将字符串转换为具有重复键的对象到数组

合并一个多维数组中键的值相同的数组

有没有办法合并两个具有相同键的 JS 对象? [复制]

如何将具有相同属性的对象合并到一个数组中?