蒙戈德按第一个角色分组



我在mongodb中遇到了问题。

我想创建聚合女巫结果将是这样的:

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

我的表中有一个列words,我想根据第 words 列的第一个字符对我的记录进行分组。

我找到了sql的决心,但对蒙戈没有。

我将非常感谢您的帮助

您不显示集合中的文档的外观,但可以使用 aggregate 集合方法来执行此操作:

// 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}}})

最新更新