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

Sum multiple fields with mongo db

I am new to mongodb, I have a collection of people and some of them have values that I am interested in.
I would like to sum those values and get the number of people who had them.

{ "_id" : 001, "tot" : 10, "duration", 100}
{ "_id" : 002, "tot" : 20, "duration", 200}
{ "_id" : 003, "tot" : 20, "duration", 300}
{ "_id" : 004}
{ "_id" : 005}

I would like to get

{ "num" : 3, "tot" : 50, "duration" : 600}

Thank you very much

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

>Solution :

You can use aggregate function in mongoDB

db.collection.aggregate([
  {
    $match: {
      tot: { $exists: true } // only match documents that have a "tot" field
    }
  },
  {
    $group: {
      _id: null,
      num: { $sum: 1 }, // count the number of documents in the group
      tot: { $sum: "$tot" }, // sum the "tot" field for each document in the group
      duration: { $sum: "$duration" } // sum the "duration" field for each document in the group
    }
  },
  {
    $project: {
      _id: 0 // exclude the _id field from the output
    }
  }
])
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