Skip to content

Instantly share code, notes, and snippets.

@alexsandro-xpt
Forked from vquaiato/gist:2782117
Created May 24, 2012 15:52
Show Gist options
  • Save alexsandro-xpt/2782358 to your computer and use it in GitHub Desktop.
Save alexsandro-xpt/2782358 to your computer and use it in GitHub Desktop.
Map/Reduce no MongoDB

###Collections Salas{_id} Reservas{_id, sala_id, data}

###Preciso contar as reservas de cada sala por uma data:

map = function () {
    emit(this.sala_id, [1]);
}
reduce = function (sala, values) {
    var sum = 0;
    if (values) {
        for (var i = 0; i < values.length; i++) {
            sum += 1;
        }
    }
    return {sala:sala, total:sum};
}
db.reservas.mapReduce(map, reduce, {"out":"resultado"})

###Problema: Quando existe apenas 1 reserva para uma sala, o reduce não é chamado:

db.resultado.find({})
{ "_id" : ObjectId("4fbd6d5b700f6e1266000002"), "value" : [ 1 ] }
{ "_id" : ObjectId("4fbd6e69700f6e1266000004"), "value" : { "sala" : ObjectId("4fbd6e69700f6e1266000004"), "total" : 2 } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment