MongoCollection::getName
MongoCollection::insert
MongoCollection
PHP Manual

# MongoCollection::group

(PECL mongo >=0.9.2)

MongoCollection::group — Performs an operation similar to SQL's GROUP BY command

### Descrição

public array MongoCollection::group ( mixed `$keys` , array `$initial` , MongoCode `$reduce` [, array `$condition` = array() ] )

### Parâmetros

`keys`

  Fields to group by. If an array or non-code object is passed, it will be the key used to group results.

  1.0.4+: If `keys` is an instance of MongoCode, `keys` will be treated as a function that returns the key to group by (see the "Passing a `keys` function" example below).

`initial`

  Initial value of the aggregation counter object.

`reduce`

  A function that takes two arguments (the current document and the aggregation to this point) and does the aggregation.

`options`

  Optional parameters to the group command. Valid options include:

  - "condition"

    Criteria for including a document in the aggregation.

  - "finalize"

    Function called once per unique key that takes the final output of the reduce function.

### Valor Retornado

Returns an array containing the result.

### Exemplos

Exemplo #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);
?>`

O exemplo acima irá imprimir algo similar a:

    array(4) {
      ["retval"]=>
      array(1) {
        [0]=>
        array(1) {
          ["count"]=>
          float(1)
        }
      }
      ["count"]=>
      float(1)
      ["keys"]=>
      int(1)
      ["ok"]=>
      float(1)
    }

Exemplo #2 Passing a `keys` function

If you want to group by something other than a field name, you can pass a function as the first parameter of MongoCollection::group() and it will be run against each document. The return value of the function will be used as its grouping value.

This example demonstrates grouping by the num field modulo 4.

`<?php
$c->group(new MongoCode('function(doc) { return {mod : doc.num % 4}; }'),
array("count" => 0),
new MongoCode('function(current, total) { total.count++; }'));
?>`

MongoCollection::getName
MongoCollection::insert
MongoCollection
PHP Manual