//Speed up MongoDB Map Reduce, http://edgystuff.tumblr.com/post/54709368492 //MongoDB as a pure in-memory, http://edgystuff.tumblr.com/post/49304254688 db.notas.ensureIndex({c:1}); //db.notas.ensureIndex({p:-1}); //6786ms db.notas.ensureIndex({a:1}); db.alunos.find().forEach(function(a){ db.notas.update({c:a._id,p:{$gte:a.p}},{$set:{v1:1}},{multi:true}) }); db.grade.find().forEach(function(g){ db.notas.update({a:g.ca},{$set:{v2:1}},{multi:true}) }); //db.notas.aggregate( //7.136ms var res = db.runCommand( //1.203ms { aggregate: "notas", pipeline: [ { $match : { v1 : 1 , v2: 1 } }, { $sort : { p : -1 } }, { $group : { _id : { c : "$c", a:"$a" } , n : { $first : "$n" } } , }, { $group : { _id : { c : "$_id.c", n:"$n" } , value : { $sum : 1 } }, }, { $group : { _id : "$_id.c", ns: { $push: { n : "$_id.n" , v: "$value" } } } }, { $out: "notas_group"} ], allowDiskUse: true, } ); //printjson(res); var map = function(){ var nota = { A:0, B:0, C:0, D:0, FF:0, X:0 }; this.ns.forEach(function(n){ nota[n.n] = n.v; }); emit(this._id,nota); }; var reduce = function(key, notas) { return notas; } var finalize = function(key, notas){ var sum = notas.FF + notas.X + notas.D + notas.C + notas.B + notas.A; var div = notas.FF + (notas.X/2) + (notas.D/3) + (notas.C/6) + (notas.B/8) + (notas.A/10); notas.I3 = sum / div; return notas; } db.notas_group.mapReduce( map, reduce, //2.022ms { finalize: finalize, out: { replace : "alunoI3" }, //sort: { "_id.c":1 }, jsMode: true, });