I am trying to query below document structure
{
_id: '7ja9sjkadja',
parent: {
parentName: 'Super',
firstGenerations: [
{
name: 'First Generation',
secondGenerations: [
{
name: 'Second Generation 1',
value: 'Married'
},
{
name: 'Second Generation 2',
value: 'Single'
},
{
name: 'Second Generation 3',
value: 'Single'
}
]
}
]
}
}
Expected output:
{
firstGenerationName: 'First Generation',
totalCount: 3
values: [
{
categoryName: 'Married (1)',
count: 1,
firstGenerationName: 'First Generation'
},
{
categoryName: 'Single (2)',
count: 2,
firstGenerationName: 'First Generation'
}
]
}
Query tried by me:
db.generations.aggregrate([
{ $project: { 'firstGenerations': '$parent.firstGenerations'} },
{ $unwind: '$firstGenerations'},
{ $unwind: '$firstGenerations.secondGenerations'}
{
$group: {
_id: '$_id',
count: { 'sum': '$secondGenerations.value' },
firstGenerationName: { $first: '$firstGenerations.name'}
}
}
])
I am able to unwind properly but not able to club group functionality by taking one value from parent array and count from second array.
Any help will be appreciated