It is important to remember that when using mapReduce (), the return value of the reduce () function should be the same form as the one you expect to receive in the "values" element of the reduce () function and this, in turn, should be the same. like the emit () function.
For a collection containing documents of the following type:
> db.posts.count(); 1000 > db.posts.findOne(); { "_id" : 0, "date_posted" : ISODate("2012-04-04T05:54:44.535Z"), "topic_id" : "sierra" }
The following code will produce the desired result:
<?php $conn = new Mongo("localhost:$port"); $db = $conn->test; $collection = $db->tst; $map = new MongoCode( "function() { emit( this.topic_id, { last_post: this.date_posted } ); }" ); $reduce = new MongoCode( "function(key, values) { ". "var max = ISODate('1970-01-01T00:00:00Z'); ". "values.forEach(function(val) { ". "if ( max < val.last_post ) max = val.last_post; ". "}); ". "return {last_post : max}; " . "}" ); $result = $db->command( array( "mapreduce" => "posts", "map" => $map, "reduce" => $reduce, "query" => array( "topic_id" => "alpha"), "out" => array( "merge" => "lastPosts") ) ); echo "result: "; print_r($result); $collection = $db->lastPosts; $cursor = $collection->find()->limit(6); date_default_timezone_set("UTC"); foreach( $cursor as $doc ) { $date = date( "r", $doc['value']['last_post']->sec ); echo $doc['_id'] . " last visited at " . $date ."\n" ; } ?>
source share