Sokil\Mongo\Pipeline::group PHP Méthode

group() public méthode

Groups documents by some specified expression and outputs to the next stage a document for each distinct grouping. The output documents contain an _id field which contains the distinct group by key. The output documents can also contain computed fields that hold the values of some accumulator expression grouped by the $group‘s _id field. $group does not order its output documents.
public group ( array | callable $stage ) : Pipeline
$stage array | callable
Résultat Pipeline
    public function group($stage)
    {
        if (is_callable($stage)) {
            $configurator = $stage;
            $stage = new GroupStage();
            call_user_func($configurator, $stage);
        }
        if ($stage instanceof GroupStage) {
            $stage = $stage->toArray();
        }
        if (!is_array($stage)) {
            throw new Exception('Group stage must be array or instance of Sokil\\Mongo\\Pipeline\\GroupStage or callable');
        }
        if (!isset($stage['_id'])) {
            throw new Exception('Group field in _id key must be specified');
        }
        $this->addStage('$group', $stage);
        return $this;
    }

Usage Example

 public function testSubtract_CallableExpressin()
 {
     $pipeline = new Pipeline($this->collection);
     $pipeline->group(function ($stage) {
         /* @var $stage \Sokil\Mongo\Pipeline\GroupStage */
         $stage->setId('user.id')->sum('totalAmount', function ($expression) {
             /* @var $expression \Sokil\Mongo\Pipeline\Expression */
             $expression->subtract(function ($expression) {
                 $expression->multiply('$amount', 3.15);
             }, 0.95);
         });
     });
     $this->assertEquals('[{"$group":{"_id":"user.id","totalAmount":{"$sum":{"$subtract":[{"$multiply":["$amount",3.15]},0.95]}}}}]', (string) $pipeline);
 }
All Usage Examples Of Sokil\Mongo\Pipeline::group