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

>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
    }
  }
])

Leave a Reply