2017-08-09 73 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