MongoCollection::group PHP Method

group() public method

Performs an operation similar to SQL's GROUP BY command
public group ( mixed $keys, array $initial, MongoCode | string $reduce, array $condition = [] ) : array
$keys mixed Fields to group by. If an array or non-code object is passed, it will be the key used to group results.
$initial array Initial value of the aggregation counter object.
$reduce MongoCode | string A function that aggregates (reduces) the objects iterated.
$condition array An condition that must be true for a row to be considered.
return array
    public function group($keys, array $initial, $reduce, array $condition = [])
    {
        if (is_string($reduce)) {
            $reduce = new MongoCode($reduce);
        }
        $command = ['group' => ['ns' => $this->name, '$reduce' => (string) $reduce, 'initial' => $initial, 'cond' => $condition]];
        if ($keys instanceof MongoCode) {
            $command['group']['$keyf'] = (string) $keys;
        } else {
            $command['group']['key'] = $keys;
        }
        if (array_key_exists('condition', $condition)) {
            $command['group']['cond'] = $condition['condition'];
        }
        if (array_key_exists('finalize', $condition)) {
            if ($condition['finalize'] instanceof MongoCode) {
                $condition['finalize'] = (string) $condition['finalize'];
            }
            $command['group']['finalize'] = $condition['finalize'];
        }
        return $this->db->command($command);
    }

Usage Example

 public function testGroup2()
 {
     $this->object->save(array("a" => 2));
     $this->object->save(array("b" => 5));
     $this->object->save(array("a" => 1));
     $keys = array();
     $initial = array("count" => 0);
     $reduce = "function (obj, prev) { prev.count++; }";
     $g = $this->object->group($keys, $initial, $reduce);
     $this->assertEquals(3, $g['count']);
 }
All Usage Examples Of MongoCollection::group