The following example aggregation operation pivots data to create a set of
author names grouped by tags applied to an article. Call the aggregation
framework by issuing the following command:
<?php
$m = new MongoClient("localhost");
$c = $m->selectDB("examples")->selectCollection("article");
$data = array (
'title' => 'this is my title',
'author' => 'bob',
'posted' => new MongoDate,
'pageViews' => 5,
'tags' => array ( 'fun', 'good', 'fun' ),
'comments' => array (
array (
'author' => 'joe',
'text' => 'this is cool',
),
array (
'author' => 'sam',
'text' => 'this is bad',
),
),
'other' =>array (
'foo' => 5,
),
);
$d = $c->insert($data, array("w" => 1));
$ops = array(
array(
'$project' => array(
"author" => 1,
"tags" => 1,
)
),
array('$unwind' => '$tags'),
array(
'$group' => array(
"_id" => array("tags" => '$tags'),
"authors" => array('$addToSet' => '$author'),
),
),
);
$results = $c->aggregate($ops);
var_dump($results);
?>
O exemplo acima irá imprimir:
array(2) {
["result"]=>
array(2) {
[0]=>
array(2) {
["_id"]=>
array(1) {
["tags"]=>
string(4) "good"
}
["authors"]=>
array(1) {
[0]=>
string(3) "bob"
}
}
[1]=>
array(2) {
["_id"]=>
array(1) {
["tags"]=>
string(3) "fun"
}
["authors"]=>
array(1) {
[0]=>
string(3) "bob"
}
}
}
["ok"]=>
float(1)
}