Hello Everyone,
I’m faced with an issue in my aggregation pipeline and I can’t quite find a solution, so I hopped someone could come up with an idea.
I’m aggregating data from a collection sub into a collection agg.
Example of content of the agg collection:
[{
"_id": "AAA",
"count": 2,
"location":
[
{
"country": "US",
"region": "ia",
"city": "cedar rapids",
"count": 1
},
{
"country": "AU",
"region": "vic",
"city": "melbourne",
"count": 1
}
]
}]
Currently I have an aggregation pipeline getting data from the sub collection that output data with the same format. Now I want to merge the data from my pipeline with the agg collection so that all the count are updated to be a SUM of the previous and new values.
For instance, my pipeline give me the following data:
[{
"_id": "AAA",
"count": 2,
"location":
[
{
"country": "US",
"region": "ca",
"city": "los angeles",
"count": 1
},
{
"country": "AU",
"region": "vic",
"city": "melbourne",
"count": 1
}
]
}]
And i want the final data to look like this:
[{
"_id": "AAA",
"count": 4,
"location":
[
{
"country": "US",
"region": "ia",
"city": "cedar rapids",
"count": 1
},
{
"country": "US",
"region": "ca",
"city": "los angeles",
"count": 1
},
{
"country": "AU",
"region": "vic",
"city": "melbourne",
"count": 2
}
]
}]
I came up with the following $merge at the end of my pipeline that sums the top count:
[
{
"$merge": {
"into": "agg",
"on": "_id",
"whenMatched": [
{
"$addFields": {
"count": {
"$add": [
"$count",
"$$new.count"
]
}
}
}
],
"whenNotMatched": "insert"
}
}]
However I have no idea on how to do the same thing for the data inside the location array.
Would someone have an idea on how to do that? I could store all my data “unwinded” and add another collection to store the aggregation of the unwind, but I don’t feel that is the adequate solution.
Thanks