Reputation: 566
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"
}
}
}
}
])
Upvotes: 0
Views: 91
Reputation: 4353
Use $reduce to sum size of each element of your array.
db.collection.aggregate([
{
$addFields: {
reactionsArray: {
$objectToArray: "$reactions"
}
}
},
{
"$project": {
reactionsSize: {
$reduce: {
input: "$reactionsArray",
initialValue: 0,
in: {
"$add": [
"$$value",
{
$size: "$$this.v"
}
]
}
}
},
},
}
])
Upvotes: 2
Reputation: 1419
You have to $unwind reactionsArray
and then use $group to get total count
db.collection.aggregate([
{
$addFields: {
reactionsArray: {
$objectToArray: "$reactions"
}
}
},
{
$unwind: "$reactionsArray"
},
{
$group: {
_id:"$_id",
numberOfReactions: {
$sum: {
$size: "$reactionsArray.v"
}
}
}
}
])
Upvotes: 1