1
votes

map code:

$map = new MongoCode("function(){
                emit(333,this);
}");

reduce code:

$reduce = new MongoCode("function(key, values) {
        r=0;
        for(var idx=0;idx<values.length;idx++){
                r+=1;
        }
        return r;
}");

run code:

$result = $db->command(array(
    "mapreduce" => "gameLog",
    "map" => $map,
    "reduce" => $reduce,
    "out" => array("replace" => "gameLogResult")
   )
);

the run code return: Array ( [result] => gameLogResult [timeMillis] => 284 [counts] => Array ( [input] => 18864 [emit] => 18864 [reduce] => 189 [output] => 1 )

[ok] => 1

) the map-reduce result is that { "_id" : 333, "value" : 65 },bug i supposed result is that { "_id" : 333, "value" : 18864 } Who can tell me why is this,Help me!

1
This is because of batching, the reduce function CAN and WILL run multiple times, once per 100 batches adding 101 results into the next batch, also you need to reduce what your emiting not something completely different - Sammaye

1 Answers

0
votes

I answered a similar question here, with an explanation of how the Map/Reduce batching works in a simple case.

I'm a little confused what you are trying to do here. If you are just looking to count the records, why not just use db.gameLog.count()? If you do want to use a Map/Reduce to count records, you can do something like this (not optimum, but simplest to understand):

map = function(){
    emit("arbitrary_key", 1)
}

reduce = function(key, values){
    var total = 0;
    for (var i = 0; i < values.length; i++) {
        total += values[i];
    }
    return total;
}