I have these types of objects in the DB.
[
{ data: { key: 'A', value: 'one' } },
{ data: { key: 'A', value: 'one' } },
{ data: { key: 'A', value: 'two' } },
{ data: { key: 'A', value: 'one' } }
]
I tried the following Aggregate
{
$group: {
_id: { key: "$data.key", value: "$data.value" },
count: { $sum: 1 },
}
},
And I got the following result:
[
{ _id: { key: 'A', value: 'two' }, count: 1 },
{ _id: { key: 'A', value: 'one' }, count: 3 }
]
How can I structure my pipeline to get the results I want?
[
{
key: 'A',
result : [
{ value: 'one', count: 3 },
{ value: 'two', count: 1 },
]
}
]