I derived the following data using the aggregate of 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?
If possible, I would like to process it using mongodb aggregate.
CodePudding user response:
$unwind
deconstruct theguguns
array$mergeObjects
to merge current object ofguguns
with other$group
by_id
andguguns.gugun
property and get required fields first value andguguns
merged object$group
by only_id
and get required fields first value and construct the array ofguguns
object
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" }
}
}
])