[英]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
數組$mergeObjects
合並的當前對象guguns
與其他$group
by _id
和guguns.gugun
屬性並獲取必填字段第一個值和guguns
合並對象$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" }
}
}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.