Skip to content

Instantly share code, notes, and snippets.

@twinsdbv
Created November 1, 2015 18:02
Show Gist options
  • Save twinsdbv/7c93c4f8a51ae3f81b26 to your computer and use it in GitHub Desktop.
Save twinsdbv/7c93c4f8a51ae3f81b26 to your computer and use it in GitHub Desktop.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/school', function(err, db) {
if(err) throw err;
var cursor = db.collection('students').find().sort({'name': -1, 'scores': -1});
cursor.each(function(err, doc) {
if(err) throw err;
if(doc == null) {
return db.close();
}
var scores = doc.scores;
var tempScore = false;
for (var key in scores) {
if (scores[key].type == 'homework') {
if (! tempScore) {
tempScore = scores[key];
} else {
if (tempScore.score <= scores[key].score) {
// remove temp score
db.collection('students').update({_id: doc._id}, {$pull: {scores: tempScore}});
// set new temp score
tempScore = scores[key];
} else {
// remove current score
db.collection('students').update({_id: doc._id}, {$pull: {scores: scores[key]}});
}
}
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment