Php Symfony Mongo查询:选择max

Php Symfony Mongo查询:选择max,php,mongodb,symfony,mongodb-query,query-builder,Php,Mongodb,Symfony,Mongodb Query,Query Builder,我试图了解聚合在mongo查询中是如何工作的。例如,我有文档产品和类别字段。如何从每个类别中选择最新添加的产品 class Product { /** * @MongoDB\Id */ protected $id; /** * @MongoDB\Field(type="integer") */ protected $category; 这就是我迄今为止所尝试的: class ProductReposito

我试图了解聚合在mongo查询中是如何工作的。例如,我有文档
产品
类别
字段。如何从每个类别中选择最新添加的产品

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();
    }
}

当我运行此查询时,我得到
未捕获的PHP异常原则\MongoDB\Exception\ResultException:“not code”

要检索上一个产品,请按id desc对它们进行排序,然后将查询限制为1个元素:

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

     $qb->sort('p.id', 'desc')
        ->from('UserBundle\Product', 'p')
        ->limit(1)
     ;

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

这个实体查询生成器!这不适用于mongo文档对于任何未来发现此问题的人来说,user4666065完全正确,这是ORM而不是ODM。正确答案可在以下网址找到: