Created
September 27, 2010 11:38
-
-
Save hubgit/598892 to your computer and use it in GitHub Desktop.
GROUP BY in MongoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This example is very helpfull. Thanks!