I need to $group Mongodb data according field A and the result should contain the count of field B items which is array. For example if data looks like:
{A: 1, B: [1, 2, 3]}
{A: 1, B: [4, 2]}
{A: 2, B: [1]}
{A: 2, B: [2, 3]}
{A: 2, B: [1, 2, 3]}
the result should look like:
{A: 1, countB: 5}
{A: 2, countB: 6}
I have a solution with $unwind like:
[
{
$unwind: "$B"
},
{
$group: {
"_id": "$A",
"countB": {$sum: 1}
},
{
$project: {
"_id": 0,
"A": "$_id.A",
"countB": "$countB"
}
}
]
My question is if it is possible to do it without $unwind stage?
Thank you.