下面让我们使用group操作,根据group_id分组,汇总计算count,用MapReduce实现:<?php
ini_set('mongo.native_long', 1);
$instance = new Mongo();
$instance = $instance->selectCollection('test', 'test');
for ($i = 0; $i < 10; $i++) {
$instance->insert(array(
'group_id' => rand(1, 5),
'count' => rand(1, 5),
));
}
?>
参数说明:db.runCommand(
{ mapreduce : <collection>,
map : <mapfunction>,
reduce : <reducefunction>,
out : <see output options below>
[, query : <query filter object>]
[, sort : <sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces>]
[, limit : <number of objects to return from collection, not supported with sharding>]
[, keeptemp: <true|false>]
[, finalize : <finalizefunction>]
[, scope : <object where fields go into javascript global scope >]
[, jsMode : true]
[, verbose : true]
}
);
<?php
ini_set('mongo.native_long', 1);
$instance = new Mongo();
$instance = $instance->selectDB('test');
$map = '
function() {
emit(this.group_id, this.count);
}
';
$reduce = '
function(key, values) {
var sum = 0;
for (var index in values) {
sum += values[index];
}
return sum;
}
';
$result = $instance->command(array(
'mapreduce' => 'test',
'map' => $map,
'reduce' => $reduce,'out' => 'test_res'
));
$resData = new Mongo();
$resData = $instance->selectDB('test_res');$result = $resData->find();//$result = iterator_to_array($instance->{$result['result']}->find());
var_dump($result);
?>