How to "Group By" with MongoDB

12,408

Sometimes you may want to get an array of distinct values in a collection. You can accomplish this using the distinct() method:

$ages = $dm->createQueryBuilder('User')
->distinct('age')
->getQuery()
->execute();

http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/query-builder-api.html

Share:
12,408
Steffi
Author by

Steffi

Updated on June 15, 2022

Comments

  • Steffi
    Steffi almost 2 years

    I would like to know if there is anyway I can "group by" my results with MongoDB/Php.

    This is the code I'm using to display my rows:

    $count = $col->find(array('order_id' => array('$gt' => '0')))->count();
    

    I need to group them by order_id.

    Apparently, we cannot do a count() on a group() as find()

    WORKS: $countfind = $col->find()->count();

    DOESN'T WORK: $countgroup = $col->group($keys)->count();

    I need to count this groupby please.

    Thanks for your help.

  • JC R
    JC R over 6 years
    The problem is you can't use ->limit() when using distinct()