2

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 Answer 1

3

Quite simple using $reduce

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

Mongo Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.