Skip to content

Instantly share code, notes, and snippets.

@AstakhovArtem
Created January 30, 2014 12:33
Show Gist options
  • Save AstakhovArtem/8707515 to your computer and use it in GitHub Desktop.
Save AstakhovArtem/8707515 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;
function iterate(list, func) {
'use strict';
var i, res;
if ('length' in list && typeof list !== 'function') {
res = [];
for (i = 0; i < list.length; i += 1) {
res.push(func.call(err, list, list[i], i));
}
} else {
res = {};
for (i in list) {
if (list.hasOwnProperty(i)) {
res[i] = func.call(err, list, list[i], i);
}
}
}
return res;
}
db.collection('students').find().sort([['name', 1], ['scores.score', 1]]).toArray(function(err, docs) {
if(err) throw err;
var lowScores = [];
function minScore(scores) {
var minScore;
iterate(scores, function(scores, elem, i) {
if(elem.type == "homework") {
if(!minScore){
minScore = elem.score;
} else if(minScore > elem.score) {
minScore = elem.score;
}
}
});
return minScore;
}
iterate(docs, function(docs, doc, i ) {
var obj;
obj = {
score: minScore(doc.scores),
id: doc._id
}
lowScores.push(obj);
});
iterate(lowScores, function(arr, item, i) {
var score = item.score;
var id = item.id;
console.log(score);
db.collection('students').update({_id:id}, {$pullAll: {scores: [{type: 'homework', score: score}]}}, function(err, updated) {
if(err) throw err;
console.log('successful update' + updated);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment