Say I have two documents that contain sales information.
Document 1
{
_id: ISODate("2022-07-24"),
week: 30,
productCounts: [
{
id: 34528,
count: 8
},
{
id: 34556,
count: 6
}
]
}
Document 2
{
_id: ISODate("2022-07-25"),
week: 30,
productCounts: [
{
id: 34528,
count: 4
},
{
id: 34556,
count: 6
}
]
}
My goal is to “merge” these two documents to produce another document like this:
{
_id: { week: 30 },
productCounts: [
{
id: 34528,
count: 12
},
{
id: 34556,
count: 12
}
]
}
I am trying to apply the concept from Example 1, Alternative 1 on this page: https://www.mongodb.com/docs/manual/reference/map-reduce-to-aggregation-pipeline/
At the moment, my aggregation pipeline looks like this:
[
{
$unwind: {
path: '$productCounts'
}
},
{
$group: {
_id: 'id',
totalCount: {
$sum: '$count'
}
}
}
]
How can I use the aggregation pipeline to create a single document containing the results from the group stage?