Search code examples
mongodbnosqlaggregation-frameworknosql-aggregation

MongoDB sum of all fields with integer values


inside the aggregation framework, it's possibile in some way, for each document like this below:

{
  "Title": "Number orders",
  "2021-03-16": 3,
  "2021-03-15": 6,
  "2021-03-19": 1,
  "2021-03-14": 19
}

Obtain a new document like this?

{
  "Title": "Number orders",
  "2021-03-16": 3,
  "2021-03-15": 6,
  "2021-03-19": 1,
  "2021-03-14": 19
  "Total": 29
}

Basically, I want a new field that have inside the sum of all the values of the fields that are integer.

Another thing to take in consideration is that the date fields are dynamic, so one week could be like the one in the example, the following week the fields would become like

{
  "Title": "Number orders",
  "2021-03-23": 3,
  "2021-03-22": 6,
  "2021-03-26": 1,
  "2021-03-21": 19
}

Thanks!


Solution

  • Demo - https://mongoplayground.net/p/724nerJUQtK

    $$ROOT is the entire document, add total using $addFields use $sum to add them up and remove allData using $unset

    db.collection.aggregate([
      { $addFields: { allData: { "$objectToArray": "$$ROOT" } } } },
      { $addFields: { "total": { $sum: "$allData.v" } } },
      { $unset: "allData" }
    ])