Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

aggregation sum elements in array in mongoDB

I have some data like that:

{id: 1, myData: [[2, 0, 0], [0, 0, 0, 3, 0, 0], [1, 0, 0, 1, 0, 0, 1, 0, 0]]}
{id: 2, myData: [[11, 0, 0], [0, 0, 0], [1, 1, 2]]}

I need to sum all numbers in each array to unique total vaule.

Desired output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{id:1, sumData: 8}
{id:2, sumData: 15}]

I tried to fix through group aggregation, but it is not working:

{
    $group:
        {
        _id: "$id",
        myDataSum: {
          $sum: "$myData",
        },
      },
}

How could I get the sum for all fields?

>Solution :

One option is to use $sum inside a $reduce:

db.collection.aggregate([
  {$project: {
      sumData: {$reduce: {
          input: "$myData",
          initialValue: 0,
          in: {$add: [
              "$$value",
              {$sum: "$$this"}
          ]}
      }}
  }}
])

See how it works on the playground example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading