获取所有有type=sale这样的"event"的用户,以及他们分别有几个这样的"event"(注:此处的event是一个集合的名字)
<?php
// sample event document
$events->insert(array("user_id" => $id,
"type" => $type,
"time" => new MongoDate(),
"desc" => $description));
// construct map and reduce functions
$map = new MongoCode("function() { emit(this.user_id,1); }");
$reduce = new MongoCode("function(k, vals) { ".
"var sum = 0;".
"for (var i in vals) {".
"sum += vals[i];".
"}".
"return sum; }");
$sales = $db->command(array(
"mapreduce" => "events",
"map" => $map,
"reduce" => $reduce,
"query" => array("type" => "sale"),
"out" => array("merge" => "eventCounts")));
$users = $db->selectCollection($sales['result'])->find();
foreach ($users as $user) {
echo "{$user['_id']} had {$user['value']} sale(s).\n";
}
?>