Get all users with at least on "sale" event, and how many times each
of these users has had a sale.
<?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";
}
?>
Note:
Using MongoCode
This example uses MongoCode, which can also take a
scope argument. However, at the moment, MongoDB does not support using
scopes in MapReduce. If you would like to use client-side variables in the
MapReduce functions, you can add them to the global scope by using the
optional scope field with the database command. See the
» MapReduce documentation
for more information.
Note:
The out argument
Before 1.8.0, the out argument was optional. If you did
not use it, MapReduce results would be written to a temporary collection,
which would be deleted when your connection was closed. In 1.8.0+, the
out argument is required. See the
» MapReduce documentation
for more information.