I have documents with a number of tokens in text, one document for a text. I need to calculate a total token count across documents. I don't know the exact number and keys of these fields, so I cannot use $sum for each field individually.
For example, I have two documents:
{
"count": {
"a": 1,
"b": 5,
"c": 7
}
}
{
"count": {
"a": 4,
"c": 2,
"d": 6
}
}
I want to aggregate them and get
{
"count": {
"a": 5,
"b": 5,
"c": 9,
"d": 6
}
}
As I understand, it is not possible, but I just wanted to make sure
CodePudding user response:
Maybe something like this:
db.collection.aggregate([
{
$set: {
count: {
"$objectToArray": "$count"
}
}
},
{
$unwind: "$count"
},
{
$group: {
_id: "$count.k",
v: {
$sum: "$count.v"
}
}
},
{
$project: {
v: 1,
k: "$_id",
_id: 0
}
},
{
$group: {
_id: "total",
count: {
$push: {
k: "$k",
v: "$v"
}
}
}
},
{
$project: {
_id: 0,
count: {
"$arrayToObject": "$count"
}
}
}
])
Explained:
Convert the objects to array(to be easy to manipulate unknown number of fields )
Unwind the array
group by the keys , sum the values.
project the necessary key / values.
group all in single array
Project to convert the array to object as per the expectations