如何在 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
数组
$mergeObjects
将guguns
的当前对象与其他对象合并
$group
by _id
和 guguns.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 的数组中合并具有相同键的对象?的主要内容,如果未能解决你的问题,请参考以下文章