Created
March 7, 2011 06:39
-
-
Save fasthold/858159 to your computer and use it in GitHub Desktop.
利用 mongodb mapreduce 计算数量总和
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$mongo = new Mongo(); | |
$db = $mongo->selectDb('firv_exam'); | |
// 要查询的collection | |
$collection = 'question'; | |
// 构造 map 和 reduce 函数 | |
$map = <<<MAP | |
function() { emit(this.username,1); } // this.username 相当于 sql 里的 group by username | |
MAP; | |
$reduce = <<<REDUCE | |
function(k, values) { | |
var total = 0; | |
for (var i = 0; i < values.length; i++) { | |
total += values[i]; | |
} | |
return total; | |
} | |
REDUCE; | |
$map = new MongoCode($map); // optional | |
$reduce = new MongoCode($reduce); // optional | |
$result = $db->command(array( | |
"mapreduce" => $collection, | |
"map" => $map, | |
"reduce" => $reduce, | |
'keeptemp' => false, | |
"query" => array("type" => "sale"), // map 查询基础条件 | |
// 'out' => 'count', // 指定查询结果输出到一个collection中。可做统计汇总表用 | |
)); | |
// $result['ok'] 为 1 表示执行成功了 | |
if($result['ok']) { | |
// $result['result'] 实际上是一个系统用于保存汇总结果的临时 collection 名称 | |
$col = $db->selectCollection($result['result']); | |
// 既然是一个 collection ,就能执行各种条件查询,进行二次筛选 | |
// 例如,取汇总表中,value 大于 20 的那些结果 | |
$rs = $col->find(array('value'=>array('$gt'=>20))); | |
print_r(iterator_to_array($rs)); | |
} else { | |
var_dump($result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment