Here's my code to do an equivalent of a GROUP BY and a SUM
<?php
$contributionCol = $db->customers->contribution;
$group = $contributionCol->group(array('date' => true), array('sum' => 0), "function (obj, prev) { prev['sum'] += obj.amount; }");
?>
This groups by the 'date' column and sums over the 'amount' column. In my testing this was much slower than querying all rows and doing the Group by code with PHP. It could just be my particular setup and data set.
Also at first my amount column was a string, which caused the results to be concatenated rather than arithmetic addition, something else to watch out for.
MongoCollection::group
(PECL mongo >=0.9.2)
MongoCollection::group — Performs an operation similar to SQL's GROUP BY command
Описание
public array MongoCollection::group
( array $keys
, array $initial
, string $reduce
[, array $condition = array()
] )
Параметри
- keys
-
Fields to group by.
- initial
-
Initial value of the aggregation counter object.
- reduce
-
A function that aggregates (reduces) the objects iterated.
- condition
-
An condition that must be true for a row to be considered.
Връщани стойности
Returns an array containing the result.
Примери
Example #1 MongoCollection::group() example
<?php
$collection->save(array("a" => 2));
$collection->save(array("b" => 5));
$collection->save(array("a" => 1));
// use all fields
$keys = array();
// set intial values
$initial = array("count" => 0);
// JavaScript function to perform
$reduce = "function (obj, prev) { prev.count++; }";
// only use documents where the "a" field is greater than 1
$condition = array("a" => array( '$gt' => 1));
$g = $collection->group($keys, $initial, $reduce, $condition);
var_dump($g);
?>
Примерът по-горе ще изведе нещо подобно на:
array(1) {
[0]=>
array(1) {
["count"]=>
int(1)
}
}
nick at pitchinteractive dot com
05-Jan-2012 12:51
Evgeniy Abduzhapparov
12-Nov-2010 05:05
Here I am posting how I get tags from my documents. Documents should have 'tags' field which is array of strings:
{'tags':['php', 'mongo']}
<?php
$keys = array();
$initial = array('tags'=>array(), 'count'=>0);
$reduce = 'function (doc, total) { if (doc.tags.length) {doc.tags.forEach(function (e) {total.tags[e]=total.tags[e]||0; total.tags[e]++; total.count++;});} }';
$criteria = array(
'condition' => array(
'tags' => array('$exists'=>true)
),
);
?>
