Symfony2 Mongodb聚合 - 获取字段的最大值

时间:2016-12-02 03:09:33

标签: mongodb symfony doctrine-odm

想要获取该记录的speed字段及其相应的其他字段的最大值。

有这个MongoDB查询:

db.Neo.aggregate({
    $group: {
        _id: '$name',
        date: { $first: '$date' },
        neo_reference_id: { $first: '$neo_reference_id' },
        name: { $first: '$name' },
        speed: {
            $max: "$speed"
        },
        is_potentially_hazardous_asteroid: { $first: '$is_potentially_hazardous_asteroid' }        
    }        
});

现在我使用Symfony2和mongo-odm-aggregation-bundle,想要执行此查询:

public function neofastestAction() {

    $expr = new \Solution\MongoAggregation\Pipeline\Operators\Expr;
    $aq = $this->get('doctrine_mongodb.odm.default_aggregation_query')->getCollection('NeoNasaBundle:Neo')->createAggregateQuery();

    $result = $aq->group(['_id'=>'$name' ])
        ->getQuery()->aggregate()->toArray();        
    $serializer = $this->get('jms_serializer');
    $response = $serializer->serialize($result,'json');
    return new Response($response);
}

执行它,但只打印_id。如何从上面构建我的MondoDB查询到Symfony2 mongo-odm-aggregation-bundle(https://packagist.org/packages/solution/mongo-odm-aggregation-bundle)并获取最后一行?它应该是speed的最高值,因此是最快的小行星。

感谢。

1 个答案:

答案 0 :(得分:0)

这样做:

public function neofastestAction() {

      $expr = new \Solution\MongoAggregation\Pipeline\Operators\Expr;
      $aq = $this->get('doctrine_mongodb.odm.default_aggregation_query')->getCollection('NeoNasaBundle:Neo')->createAggregateQuery();

      $result = $aq->group(['_id'=>'$name', 'date'=> $expr->first('$date'),  'neo_reference_id'=> $expr->first('$neo_reference_id'), 'name'=> $expr->first('$name'), 'speed'=> $expr->max('$speed'),'is_potentially_hazardous_asteroid'=> $expr->first('$is_potentially_hazardous_asteroid') ])
             ->sort(['speed' => -1])->limit(1)->getQuery()->aggregate()->toArray();


      $serializer = $this->get('jms_serializer');
      $response = $serializer->serialize($result,'json');

      return new Response($response);
    }