Fetching sum of rows for a type of column value in mongodb as a single output

Viewed 60

I am trying to get the sum of field 'score.number' based on the type of a column value work.type in MongoDB. It should fetch sum as 25 for 'hw' ,and 'cw' as 5 as a single output for the student 'A'. Is there a way to achieve it using mongodb queries ? I tried the $group as well but it doesn't seem to fetch the worktype and the sum for each worktype against it for a single student record 'A'.

enter image description here

Expected Output:

enter image description here

3 Answers

after $match you should use $group like this

db.collection.aggregate([
  {
    $match: {
      student: {
        $in: [
          "A"
        ]
      },
      "work.type": {
        $in: [
          "hw",
          "cw"
        ]
      }
    }
  },
  {
    "$group": {
      "_id": {
        "worktype": "$work.type",
        "student": "$student"
      },
      "workScore": {
        "$sum": "$score.number"
      }
    }
  }
])

https://mongoplayground.net/p/qzghM5KoAbp

Able to get the sum with these two

$match{
  
      'student': {'$in': ['A']},
      "work.type": {'$in': ['hw', 'cw']},
 }

followed by

     $group
    {
       _id: '$work.type',
        totalAmount: { $sum: "$score.number" },
    }
$match  {'student': {
        $in: [
          "A"
        ]
      },
      "work.type": {
        $in: [
          "hw",
          "cw"
        ]
      }}
followed by 
  $group  {
  "_id": {
        "worktype": "$work.type",
        "student": "$student"
      },
      "workScore": {
        "$sum": "$score.number"
      }
}
followed by
    $group {"_id": {
        "student": "$_id.student"
      },
  'list': {'$push': {'worktype':"$_id.worktype", 'workScore': "$workScore" }},
 }    

Solved output:

enter image description here

Solves the issue.

Related