I am using a training grades database from MongoDB. It is structured as follows.
"_id": {
"$oid": "56d5f7eb604eb380b0d8d8fa"
},
"class_id": {
"$numberDouble": "173"
},
"scores": [
{
"score": {
"$numberDouble": "19.81430597438296"
},
"type": "exam"
},
{
"score": {
"$numberDouble": "16.851404299968642"
},
"type": "quiz"
},
{
"score": {
"$numberDouble": "60.108751761488186"
},
"type": "homework"
},
{
"score": {
"$numberDouble": "22.886167083915776"
},
"type": "homework"
}
],
"student_id": {
"$numberDouble": "4"
}
}
I am trying to run aggregation which returns all documents grouped first by class_id and then by student_id with all homework scores like the following.
{
class_id: 3,
all_scores: [
{
student_id: 110,
scores : [
{
type: "homework",
score: 89.98
},
{
type: "homework",
score: 90.98
},
]
},
{
student_id:190,
scores : [
{
type: "homework",
score: 18.98
},
{
type: "homework",
score: 99.98
},
]
},
]
}
I am running the following aggregation function.
[
{
'$unwind': {
'path': '$scores'
}
}, {
'$match': {
'scores.type': 'homework'
}
}, {
'$group': {
'_id': '$class_id',
'scores': {
'$push': {
'type': '$scores.type',
'score': '$scores.score',
'student_id': '$student_id'
}
}
}
}
]
But it is returning the following result:
{
_id: 3,
scores: [
{
"type": "homework",
"score": 89.98,
"student_id": 110
},
{
"type": "homework",
"score": 90.98,
"student_id": 110
},
{
"type": "homework",
"score": 18.98,
"student_id": 190
},
{
"type": "homework",
"score": 99.98,
"student_id": 190
},
]
}
If even if there are multiple objects in the scores array, it is not combining them with the student_id group and shows them separate. I am not sure of what I should add to the aggregation. Any help would be appreciated!