Skip to content

How to do Map Reduce

ichikaway edited this page Apr 22, 2011 · 9 revisions

In controller, using Post model.

<?php
  $map = new MongoCode("function() { emit(this.title,1); }");
  $reduce = new MongoCode("function(k, vals) { ".
      "var sum = 0;".
      "for (var i in vals) {".
      "sum += vals[i];".
      "}".
      "return sum; }"
      );

  $params = array(
      "mapreduce" => "posts",
      "map" => $map,
      "reduce" => $reduce,
      "query" => array(
        "count" => array('$gt' => 2),
        ),
      'out' => 'test_mapreduce_posts', //must above MongoDB1.8
      );

  $mongo = $this->Post->getDataSource();
  $results = $mongo->mapReduce($params);

  //if you want to set timeout, use 2nd param of mapReduce().
  //timeout is milli second. This example set 100msec.
  //  $results = $mongo->mapReduce($params, 100);

Other good sample is here, thanks rross0227. https://gist.github.com/931994

FYI

http://www.mongodb.org/display/DOCS/MapReduce

http://php.net/manual/en/mongodb.command.php