I have a collection as:
{
userId: ObjectId("..."),
action: {
type: "predefined value",
key1: "key1Value",
key2: "key2Value",
key3: "key3Value"
}
},{
userId: ObjectId("..."),
action: {
type: "predefined value",
key1: "key1aValue"
}
},
{
userId: ObjectId("..."),
action: {
type: "predefined value",
key3: "key3Value",
key4: "key4Value"
}
}
By aggregating to the first stage I make a match for the requested userId and I can count the values of a specific key.
[
{
'$match': {
'userId': new ObjectId('62e3aa7cd4524678b541f4fc')
}
}, {
'$group': {
'_id': '$action.key1',
'count': {
'$sum': 1
}
}
}
]
This way I get this ouput
[
{_id: "key1Value", count: 1},
{_id: "key1aValue", count: 1}
]
How can I get through a single aggregate the count of values for each single key as in the output below?
[
key1: [
{_id: "key1Value", count: 1},
{_id: "key1aValue", count: 1}
],
key2: [
...
],
key3: [
...
],
....
]