$sum fields in $group across dataset in MongoDB

@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