I have a database structure which includes the following object:
"reactions": {
"👊": [
"5f3c569e70441a0017511fe2",
"5f88d49dbf1b850017e28f4e",
"5f488189b0c5970017aa8c7a"
],
"😋": [
"5f539086cfb52a00176089ed"
]
}
I want to be able to count the "number of reactions" (a total of all the nested elements) - so in this case, the expected result would be 4.
I tried the following, and this successfully counts the number of keys - the result is 2, but not the total number of values - which should be 4.
db.collection("posts").aggregate([{
{
$addFields: {
reactionsArray: {
$objectToArray: "$reactions"
}
}
},
{
$addFields: {
numberOfReactions: {
$sum: {
$size: "$reactionsArray.v"
}
}
}
}
])