开发者

How to "Group By" with MongoDB

I would like to know if there is anyway I can "gr开发者_C百科oup 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.


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


There's some detailed documentation on the Group command on their website.

There are some examples of Group using the PHP libarary here.

If your data set is really big, you may need to look at running map-reduces to "pre-group" this data.


New answer using Mongo aggregation framework

After this question was asked and answered, 10gen released Mongodb version 2.2 with an aggregation framework. So the new best way to do Group By is with the $group operator. In PHP use MongoCollection::aggregate.

FYI, 10gen also has a handy SQL to Mongo Aggregation conversion chart worth bookmarking. It has examples of all the common SQL queries that use SQL aggregation and how to translate them to Mongo.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜