scala mongodb groupby 多个字段
今天同事问groupby多个字段是怎么写的
然后上$group (aggregation)
看了下,发现要写表达式,看了这篇文章MongoDB aggregate 运用篇 个人总结,发现要像如下写:
1 |
|
那么代码中应该怎么写呢,研究了半天,看到这篇文章MongoDB getCollection with a specific document class
发现我们得从定义mongodbClient开始定义个codeRegistry
1 |
|
然后在用的地方直接
1 | val groupBy = group(GroupByCode("$userType","$code"),sum("count", 1)) |
当然mongodb-scala-driver得升级到2.0版才支持caseClassCodec
New in 2.0, the Scala driver allows you to use case classes to represent documents in a collection via the Macros helper. Simple case classes and nested case classes are supported. Hierarchical modelling can be achieve by using a sealed trait and having case classes implement the parent trait.