Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "Group By" with MongoDB

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.

like image 437
Steffi Avatar asked Jul 09 '10 16:07

Steffi


People also ask

How does group work in MongoDB?

The $group stage groups the documents by date and calculates the total sale amount, average quantity, and total count of the documents in each group. Third Stage: The $sort stage sorts the results by the total sale amount for each group in descending order.

How is documents grouped in MongoDB?

Groups documents by some specified expression and outputs to the next stage a document for each distinct grouping. The output documents contain an _id field which contains the distinct group by key.

WHAT IS group in MongoDB aggregation?

Group operator (also known as an accumulator operator) is a crucial operator in the MongoDB language, as it helps to perform various transformations of data. It is a part of aggregation in MongoDB. MongoDB is an open-source NoSQL database management program. NoSQL is an alternative to traditional relational databases.


1 Answers

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

like image 63
Евгений Раткевич Avatar answered Oct 05 '22 09:10

Евгений Раткевич