mongodb group by first character

妖精的绣舞 提交于 2020-01-03 03:48:04

问题


I have a problem in mongodb.

I want to create aggregation witch result will be like this:

A 10
B 2
C 4
D 9
E 3
...

I have a column words in my table and I want to group my records according to first character of column words.

I find resolve for sql but not for mongo.

I will be very grateful for your help


回答1:


You don't show what the docs in your collection look like, but you can use the aggregate collection method to do this:

// Group by the first letter of the 'words' field of each doc in the 'test'
// collection while generating a count of the docs in each group.
db.test.aggregate({$group: {_id: {$substr: ['$words', 0, 1]}, count: {$sum: 1}}})


来源:https://stackoverflow.com/questions/20816583/mongodb-group-by-first-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!