/** * Gets the grouping that groups everything in an array. * * @param string $field */ private function getGroup($field) { $group = new Group(); $group->setGroupBy('_id'); $condition = Condition::getConditionByIfArray(['$gte' => ['$' . $field, []]], '$' . $field . '_unwrapped', '$' . $field . '_original'); $push = new Push(); $push->setPush($condition); $group->setResultField($field, $push); return $group; }
/** * Tests grouping some data on multiple fields. */ public function testGroupDataOnMultipleFields() { $testData = [['foo' => 'foo', 'bar' => 'bar'], ['foo' => 'foo', 'bar' => 'bar'], ['foo' => 'bar', 'bar' => 'foo'], ['foo' => 'bar', 'bar' => 'bar'], ['foo' => 'bar', 'bar' => 'bar']]; foreach ($testData as $test) { $this->collection->save($test); } $group = new Group(); $group->setGroupBy(['foo', 'bar']); $sum = new Sum(); $sum->setSum(1); $group->setResultField('count', $sum); $result = $this->collection->aggregate([$group->getStage()]); $this->assertEquals(3, count($result['result'])); foreach ($result['result'] as $res) { if ($res['_id'] == ['foo' => 'foo', 'bar' => 'bar']) { $this->assertEquals(2, $res['count']); } elseif ($res['_id'] == ['foo' => 'bar', 'bar' => 'foo']) { $this->assertEquals(1, $res['count']); } else { $this->assertEquals(2, $res['count']); } } }
/** * Gets the aggregation pipeline * * @param array $query * @param string $category * @param mixed $ranges * @return array */ private function getAggregationPipeline(array $query, $category, $ranges) { $pipelineBuilder = new PipelineBuilder(); $categoryQuery = array(); $categoryQuery[] = array($category => array('$exists' => true)); if (isset($ranges) && is_array($ranges) && $this->getRangeType($ranges) === static::MINMAX) { $categoryQuery[] = array('$or' => array(array($category => array('$type' => 1)), array($category => array('$type' => 16)), array($category => array('$type' => 18)))); } unset($query[$category]); $query['$and'] = $categoryQuery; $match = new Match(); $match->setQuery($query); $pipelineBuilder->add($match); if (is_array($ranges) && static::getRangeType($ranges) === static::MINMAX) { $rangeProjection = new RangeProjection(); $rangeProjection->addRange($category, $ranges); $pipelineBuilder->add($rangeProjection); } else { $pipelineBuilder->addBuilder(new UnwindBuilder($category)); } $group = new Group(); $group->setGroupBy($category); $sum = new Sum(); $sum->setSum(1); $group->setResultField('count', $sum); $pipelineBuilder->add($group); return $pipelineBuilder->build(); }