2017-08-09 18 views
1

mongoクエリでの集計の動作を理解しようとしています。たとえば、文書Productcategoryフィールドがあります。各カテゴリから最新の製品を選択するにはどうすればよいですか?Symfony Mongoクエリ:select max

class Product { 
    /** 
     * @MongoDB\Id 
     */ 
    protected $id; 

    /** 
     * @MongoDB\Field(type="integer") 
     */ 
    protected $category; 

これは私がこれまで試したものです:

class ProductRepository extends DocumentRepository 
{ 

    public function lastProducts() 
    { 
     $qb = $this->createQueryBuilder(); 
     $qb->max('id'); 
     $qb->group(['category'], []); 

     return $qb->getQuery()->execute(); 
    } 
} 

私はこのクエリを実行すると、私はUncaught PHP Exception Doctrine\MongoDB\Exception\ResultException: "not code"

答えて

3

を取得し、あなたの結果を配置したい場所から指定し、自分の選択にMAXを追加しますそれらをグループ化します:

public function lastProducts() 
{ 
    $qb = $this->createQueryBuilder(); 

    $qb->select('MAX(p.id), p.category') 
     ->from('UserBundle\Product', 'p') 
     ->groupBy('p.category') 
    ; 

    return $qb->getQuery()->getScalarResult(); 
} 
+0

このエンティティクエリビルダ!これはmongoドキュメント – julie

0

これをMongoとSymfonyで試してみてくださいDB:

$products = $this->get('doctrine_mongodb') 
    ->getManager() 
    ->createQueryBuilder('YourFooBundle:EntityName') 
    ->sort('id', 'DESC') 
    ->limit(1) 
    ->getQuery() 
    ->execute() 

http://symfony.com/doc/3.1/bundles/DoctrineMongoDBBundle/index.html#using-the-query-builder

+0

このエンティティクエリビルダでは機能しません!これはmongoドキュメントでは機能しません – julie

+0

このクエリは、すべての製品から最後の1つの製品のみを取得します。各カテゴリから最終製品を取得するにはどうすればよいですか? – julie