Skip to content

Instantly share code, notes, and snippets.

@jeffyuhaoliu
Created August 29, 2013 06:14
Show Gist options
  • Save jeffyuhaoliu/6374727 to your computer and use it in GitHub Desktop.
Save jeffyuhaoliu/6374727 to your computer and use it in GitHub Desktop.
Node.js MongoDB HW#3.1
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/school', function(err, db) {
if(err) throw err;
db.collection('students').aggregate(
{'$unwind':'$scores'},
{'$match':{'scores.type': 'homework'}},
{'$group':{'_id':'$_id',
// 'scores':{$addToSet:'$scores.score'},
// 'type': {$addToSet:'$scores.type'},
// 'name': {$addToSet: '$name'},
'minScore': {$min: '$scores.score'}
}},
{'$sort': {'_id': 1}},
function(err, doc) {
// console.dir(doc);
// console.dir(doc.length);
for (var i = 0; i < doc.length; i++) {
var id = doc[i]._id;
var minScore = doc[i].minScore;
// console.dir(id + " : " + minScore);
db.collection('students').update(
{_id: id, 'scores.score': minScore},
{$pull: {scores: {'score': minScore}}},
function(err, updated) {
console.dir("Successfully updated " + updated + " document!");
}
);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment