コード例 #1
0
 /**
  * Basic range testing.
  */
 public function testRangeProjection()
 {
     $testData = [['foo' => 1], ['foo' => 2], ['foo' => 3], ['foo' => 5], ['foo' => 11], ['foo' => 15], ['foo' => 22], ['foo' => 29]];
     foreach ($testData as $test) {
         $this->collection->save($test);
     }
     $ranges = [['label' => 'low', 'max' => 10], ['label' => 'medium', 'min' => 11, 'max' => 20], ['label' => 'high', 'min' => 21]];
     $rangedProjection = new RangeProjection();
     $rangedProjection->addRange('foo', $ranges);
     $result = $this->collection->aggregate([$rangedProjection->getStage()]);
     $this->assertEquals(count($testData), count($result['result']));
     $lows = 0;
     $mediums = 0;
     $highs = 0;
     foreach ($result['result'] as $res) {
         switch ($res['foo']) {
             case 'high':
                 $highs++;
                 break;
             case 'medium':
                 $mediums++;
                 break;
             case 'low':
                 $lows++;
                 break;
         }
     }
     $this->assertEquals(4, $lows);
     $this->assertEquals(2, $mediums);
     $this->assertEquals(2, $highs);
 }
 /**
  * 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();
 }