mongodb按首字符分组 [英] mongodb group by first character
本文介绍了mongodb按首字符分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在mongodb中遇到问题。
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
...
我在表中有一列 words
,我想要根据列 words
的第一个字符对记录进行分组。
I have a column words
in my table and I want to group my records according to first character of column words
.
我发现的解决方法sql
,而不是mongo。
I find resolve for sql
but not for mongo.
我将非常感谢您的帮助
推荐答案
您没有显示集合中文档的外观,但是可以使用 聚合
收集方法可做到这一点:
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}}})
这篇关于mongodb按首字符分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文