先生成测试数据:

<?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),
   ));
   }
?>

下面让我们使用group操作,根据group_id分组,汇总计算count,用MapReduce实现:

MapReduc用法:

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]
}
);

参数说明:
mapreduc:要操作的目标集合。
map:映射函数(生成键值对序列,作为 reduce 函数参数)。
reduce:统计函数。
query :目标记录过滤。
sort:目标记录排序。
limit:限制目标记录数量。
out:统计结果存放集合(不指定则使用临时集合,在客户端断开后自动删除)。
keeptemp:是否保留临时集合。
finalize:最终处理函数(对 reduce 返回结果进行最终整理后存入结果集合)。
score:向 map、reduce、finalize 导入外部变量。
verbose : 显示详细的时间统计信息。

<?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);
   ?>
Tags:
Mongodb | 评论(0) | 引用(0) | 阅读(4638)
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]