Skip to content

Instantly share code, notes, and snippets.

@hubgit
Created September 27, 2010 11:38
Show Gist options
  • Save hubgit/598892 to your computer and use it in GitHub Desktop.
Save hubgit/598892 to your computer and use it in GitHub Desktop.
GROUP BY in MongoDB
<?php
$mongo = new Mongo('mongodb://localhost', array('persist' => true));
$collection = $mongo->selectDB('test')->selectCollection('group');
$collection->drop();
foreach (range(1,1000) as $i){
$name = ($i % 3 === 0) ? 'Fred' : 'Bob';
$collection->insert(array('id' => $i, 'name' => $name));
}
$collection->ensureIndex(array('name' => true));
// http://www.php.net/manual/en/mongocollection.group.php
$cursor = $collection->group(
array('name' => true), // fields to group by
array('count' => 0), // initial value of the aggregation counter object.
new MongoCode('function(doc, prev) { prev.count += 1 }'), // a function that takes two arguments (the current document and the aggregation to this point) and does the aggregation
array('id' => array('$gt' => 200)) // condition for including a document in the aggregation
);
print 'Total: ' . $cursor['count'] . "\n";
foreach ($cursor['retval'] as $item)
print "\t" . $item['name'] . ': ' . $item['count'] . "\n";
@henkealg
Copy link

henkealg commented Feb 1, 2013

This example is very helpfull. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment