0

I've been breaking my head on this for a while now:

[
  {
    "_id": "12sdsd",
    "TotalStudent": [
      "10"
    ]
  },
  {
    "_id": "22fdf",
    "TotalStudent": [
      "20"
    ]
  }
]

I need to sum the two values after conversion from String to Integer. This doesn't work:

db.collection.aggregate([
  {
    $group: {
      _id: "",
      TotalStudents: {
        $sum: {
          $toInt: "$TotalStudent.0"
        }
      }
    }
  }
])

See the playground, what am I doing wrong? https://mongoplayground.net/p/Evm3tJUGmKa

1 Answer 1

1

"$TotalStudent.0" - This is not a valid syntax with aggregation queries. When working with array fields in aggregations, use Aggregation Array Operators. The operator to get an element of an array by its index is $arrayElemAt. So, the following $group stage will work fine:

{ $group: { 
    _id: "", 
    TotalStudents: { $sum: { $toInt: { $arrayElemAt: [ "$TotalStudent", 0 ] } } } 
} }
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.