Skip to content

Instantly share code, notes, and snippets.

@ronalstal
Created November 17, 2012 21:50
Show Gist options
  • Save ronalstal/4100537 to your computer and use it in GitHub Desktop.
Save ronalstal/4100537 to your computer and use it in GitHub Desktop.
M101 HW31 Verify script for mongo-shell without using aggregate
// for mongo shell
// verify homework 3-1 without using aggregate (for Windows XP)
// "provide the identity of the student with the highest average in the class"
var maxAvg = 0;
var maxAvgId = 0;
// loop per student, calculate its' average and compare
var cursor = db.students.find();
while ( cursor.hasNext() ) {
var doc = cursor.next();
var sum = 0, count = 0;
// sum up all scores
for ( var i=0; i<doc.scores.length; i++ ) {
sum += doc.scores[i].score;
count++;
}
if ( sum/count > maxAvg ) {
maxAvg = sum/count;
maxAvgId = doc._id;
}
}; // loop students
print("result:");
print("_id: "+maxAvgId);
print("average: "+maxAvg);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment