I have a collection called notifications that has 2 fields (for simplicity):
targetsis an array of stringsuserReadsis an array of object{userId, readAt}
Example :
{
targets: ['group1', 'group2'],
userReads: [
{userId: 1, readAt: 'date1'},
{userId: 2, readAt: 'date2'},
{userId: 3, readAt: 'date3'},
]
}
{
targets: ['group1'],
userReads: [
{userId: 1, readAt: 'date4'}
]
}
DESIRED OUTPUT:
{
groupsNotificationsCount: {
group1: 2,
group2: 1
},
usersNotificationsCount: {
1: 2,
2: 1,
3: 1
}
}
At first I tried this aggregate:
[{
$match: {
targets: {
$in: ['group/1','group/2']
},
}
}, {
$project: {
targets: 1,
userReads: 1
}
}, {
$unwind: {
path: '$targets'
}
}, {
$match: {
targets: {
$in: ['group/1','group/2']
}
}
}, {
$group: {
_id: '$targets',
countForGroup: {
$count: {}
},
userReads: {
$push: '$userReads'
}
}
}, {
$addFields: {
userReads: {
$reduce: {
input: '$userReads',
initialValue: [],
'in': {
$concatArrays: [
'$$value',
'$$this'
]
}
}
}
}
}]
I have the right counts for each group in my documents like so:
{
_id: 'group1',
countForGroup: 2,
userReads: [
{userId: 1, readAt: 'date1'},
{userId: 2, readAt: 'date2'},
{userId: 3, readAt: 'date3'},
{userId: 1, readAt: 'date4'},
]
}
But now I have no idea how to go on from there to get my desired output