2

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!

Omar El Malak
  • 179
  • 1
  • 8

2 Answers2

2

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" }
])
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

Based on your older question, I think this might help:

db.collection.aggregate([
    {
        $group: {
            _id: {
                dDate: "$deliveryDay",
                name: "$plate.name"
            },
            v: { $sum: "$plate.quantity" }
        }
    },
    {
        $group: {
            _id: "$_id.name",
            Total: { $sum: "$v" },
            array: {
                $push: { k: "$_id.dDate", v: "$v" }
            }
        }
    },
    {
        $addFields: {
            array: {
                $concatArrays: [
                    [{ k: "Title", v: "Number orders" }],
                    "$array",
                    [{ k: "Total", v: "$Total" }]
                ]
            }
        }
    },
    {
        $replaceRoot: {
            newRoot: { $arrayToObject: "$array" }
        }
    }
])

Output:

/* 1 */
{
    "Title" : "Number orders",
    "2021-01-16" : 2,
    "Total" : 2
},

/* 2 */
{
    "Title" : "Number orders",
    "2021-01-14" : 1,
    "2021-01-16" : 3,
    "Total" : 4
}
Dheemanth Bhat
  • 4,269
  • 2
  • 21
  • 40