MongoDB Aggregate with sum of array object values

Viewed 197

I have a collection with the following data:

{ "id": 1,
  "name": "abc",
  "age" : "12"
  "quizzes": [
      {
          "id": "1",
          "time": "10"
      },
      {
          "id": "2",
          "time": "20"
      }
  ]
},
{ "id": 2,
  "name": "efg",
  "age" : "20"
  "quizzes": [
      {
          "id": "3",
          "time": "11"
      },
      {
          "id": "4",
          "time": "25"
      }
  ]
},
...

I would like to perform the MongoDB Aggregation for a sum of quizzes for each document.and set it to totalTimes field

And this is the result that I would like to get after the querying:

{ "id": 1,
  "name": "abc",
  "age" : "12",
  "totalTimes": "30"
  "quizzes": [
      {
          "id": "1",
          "time": "10"
      },
      {
          "id": "2",
          "time": "20"
      }
  ]
},
{ "id": 2,
  "name": "efg",
  "age" : "20",
  "totalTimes": "36"
  "quizzes": [
      {
          "id": "3",
          "time": "11"
      },
      {
          "id": "4",
          "time": "25"
      }
  ]
},
...

How can I query to get the sum of quizzes time?

1 Answers

Quite simple using $reduce

db.collection.aggregate([
  {
    $addFields: {
      totalTimes: {
        $reduce: {
          input: "$quizzes",
          initialValue: 0,
          in: {
            $sum: [
              {
                $toInt: "$$this.time"
              },
              "$$value"
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

Related