user4666065
user4666065

Reputation:

Symfony Mongo query: select max

I am trying to understand how aggregation works in mongo queries. For example, I have document Product with category field. How can I select latest added product from each category?

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

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

This is what I've tried so far:

class ProductRepository extends DocumentRepository
{

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

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

When I run this query I get Uncaught PHP Exception Doctrine\MongoDB\Exception\ResultException: "not code"

Upvotes: 1

Views: 814

Answers (1)

Veve
Veve

Reputation: 6758

To retrieve the last product, sort them by id desc, then limit your query to 1 element:

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

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

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

Upvotes: 2

Related Questions