How do I get the $sum
of certain fields in a group?
{
$Group: {_id: my_awesome_id},
fieldwithseconds: {$sum: "$secondsfromDB"},
grandtotalofseconds: {$sum: "$fieldwithseconds"}
}
Why is grand total not working?
I have also tried:
grandtotalofseconds: {$sum: “fieldwithseconds”}
Cheers,
Daniel
Mah_Neh
(Mah Neh)
September 6, 2022, 9:13am
2
Did you sort this out already?
I see what the issue is. I don’t think you can access the field of a document that is being generated. You can only access the ones of the document being processed.
Also, I don’t see how field with seconds isnt already what you want?
Greetings
Doing a $sum of sums is needed in my case.
But I need to sum up my sums to a grand total sum.
The base value is seconds from MongoDB but I need to sum up those seconds across the dataset.
D
alexbevi
(Alex Bevilacqua)
September 6, 2022, 10:23am
4
@Daniel_Stege_Lindsjo to do a sum of sums you’d need to $group
again to perform a $sum
of the calculated field from the previous $group
.
For example:
db.foo.drop();
db.foo.insertMany([
{ a: 1, seconds: 1 },
{ a: 1, seconds: 2 },
{ a: 2, seconds: 3 },
{ a: 2, seconds: 4 },
])
db.foo.aggregate([
{ $group: {
_id: "$a",
subTotal: { $sum: "$seconds" }
}}
])
// output
[
{
"_id": 1,
"subTotal": 3
},
{
"_id": 2,
"subTotal": 7
}
]
If you add another $group
to the above you can product a grand total from the sum of the subtotals:
db.foo.aggregate([
{ $group: {
_id: "$a",
subTotal: { $sum: "$seconds" }
}},
{ $group: {
_id: null,
results: { $push: "$$ROOT" },
grandTotal: { $sum: "$subTotal" }
}}
])
[
{
"_id": null,
"results": [
{
"_id": 1,
"subTotal": 3
},
{
"_id": 2,
"subTotal": 7
}
],
"grandTotal": 10
}
]
4 Likes
system
(system)
Closed
September 11, 2022, 10:24am
5
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.