Angelo Pitarresi - 1 year ago 88

JSON Question

I've just started using MongoDB and tried to obtain the avg grade of a student from a specific course. Most of the question here involve using aggregate, $sum or $project, I'm passing the course name and index of a student as function parameters, I tried iterating through the courses and summing the values but I guess I have a problem formulating the iteration in order to get the sum of the values of a specific student from a specific course :

`function (course, index) {`

studcourses = db.students.find({course:course});

studnr = db.students.find({index:index});

results = [];

var sum = 0;

for (var i = 0; i < studcourses.length(); i++)

{

sum = sum + studcourses[i].grades;

}

mean = sum / studcourses.length();

results.push("Mean grade from course " + course + " for index: " + index + " " + mean);

return results;

}

Here's how the students collection look like:

`{`

"_id": ObjectId("57644746473defc5128f8687"),

"index": 123345,

"name": "Andrew",

"surname": "Kaka",

"grades": {

"DMI": [

4,

5,

3,

2

],

"IABD": [

3,

5,

3,

5

],

"NPAD": [

2,

4,

5,

2,

4,

5

]

}

}

Answer

I'm assuming you are using latest version of MongoDB and NodeJS driver, try:

```
var find = function(course, idx){
var grades = "$grades." + course;
var result = db.collection.aggregate([
{$match:{"index": ix}},
{$project:{index:1, surname:1, total: {$sum: grades}, average: {$avg: grades}}}
]);
return result;
};
```

You can call above function in your code as:

```
find("IABD", 123345);
```

Assuming you are searching for course `IABD`

for student index `123345`

, code above will return

```
{
"_id" : ObjectId("57644746473defc5128f8687"),
"index" : NumberInt(123345),
"surname" : "Kaka",
"total" : NumberInt(16),
"average" : NumberInt(4)
}
```

Source (Stackoverflow)