我使用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 聚合處理它。
uj5u.com熱心網友回復:
$unwind解構guguns陣列$mergeObjects將當前物件guguns與其他物件合并$group通過_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" }
}
}
])
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/348830.html
