Matheus Oliveira
Matheus Oliveira

Reputation: 627

How to "group by" field "count" in mongodb querybuilder?

I want to classify cities with the products they have.

I have two documents: Product and city. The product has its ID and a reference to a city document:

Product(id)             City 

 P1 ------------     Atlanta

 P2 ------------     New York

 P3 ------------     Michigan

 P4 ------------     Atlanta

       ....

I want as result of the query

[Atlant => 23, New York => 35, Michigan => 23, etc..]

But I not being able to get the result.

My actual code is

   public function countBestUsers()
    {
        return $this->createQueryBuilder()
            ->select('id', 'city')
            ->distinct('city')
            ->getQuery()
            ->execute()
            ;
    }

Upvotes: 2

Views: 2631

Answers (1)

panche14
panche14

Reputation: 661

You can try with group and reduce, this example works for me:

$count = $dm->createQueryBuilder()->hydrate(false)
        ->group(array('city.$id' => 1), array('value' => 0))
        ->reduce('function (curr,result) {
            result.value++;
        }')
        ->getQuery()
        ->execute()->toArray();

If you need more examples : http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/query-builder-api.html#group-queries

If you will sort it by the quantities, I recommend use aggregate Framework:

$pipeline = array('$group' => array(
        '_id' => '$city',
        'value' => array('$sum' => 1)
    )));

array_push($pipeline, array( '$sort' => array('value' => -1) ) );

$count = $dm->getDocumentCollection('YourBundle:Product')
            ->aggregate($pipeline)->toArray();

Upvotes: 3

Related Questions