1
collection: users
fields: name, age

I wish to apply a map reduce function in PHP that will return the count for users, grouped by age and sorted by age.

I can't find any good examples in PHP using the native php-mongo driver to do this. Of course I don't want to sort on client side because the results might be huge.

johnlemon
  • 20,761
  • 42
  • 119
  • 178
  • [Here](http://stackoverflow.com/questions/3002841/mongo-map-reduce-first-time) is good example how to run m/r from php. – Andrew Orsich Jun 11 '12 at 10:13
  • @Andrew there is no sort – johnlemon Jun 11 '12 at 11:30
  • You can output the results of map reduce to a new collection, and subsequently sort this collection. If you're doing inline map reduce, there is no way to sort the results. http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Outputoptions – Jenna Jun 11 '12 at 20:43

1 Answers1

0

I am going to assume you have your connection, and collection grabbing sorted already. You will have to use the MongoCollection::group() function to get the result

$keys    = array('age' => 1);
$initial = array('count' => 0);
$reduce  = "function(doc, out) { out.count++; }";

$result = $collection->group($keys, $initial, $reduce);

var_dump($result)

As for the sort: MongoDB doesn't support sorting the result of a group, you'll have to do in php. This is because group() returns a single document and not a cursor, and it cannot be sorted before it's returned. As per documentation:

"To order the grouped data, simply sort it client-side upon return."

Kasia Gogolek
  • 3,374
  • 4
  • 33
  • 50
  • MongoDB doesn't support sorting the result of a group, you'll have to do in php. This is because group() returns a single document and not a cursor, and it cannot be sorted before it's returned. – Kasia Gogolek Jun 11 '12 at 11:38
  • in mongo docs: http://www.mongodb.org/display/DOCS/MapReduce, ] – johnlemon Jun 11 '12 at 11:46