Scala根据最大值过滤列表

时间:2016-08-31 21:24:20

标签: mongodb scala

我有以下MAP:

[
  { "animal": "dog", "age": 1},
  { "animal": "dog", "age": 2},
  { "animal": "dog", "age": 3},
  { "animal": "cat", "age": 1},
  { "animal": "cat", "age": 4},
  { "animal": "rabbit", "age": 9}
]

如何返回结果,以便获得最大年龄的狗,猫和兔子。例如:

[
    { "animal": "dog", "age": 3},    # oldest dog in DB
    { "animal": "cat", "age": 4},    # oldest cat in DB
    { "animal": "rabbit", "age": 9}  # oldest rabbit in DB

]

我试图使用两个scala .map()聚合来获取此功能但到目前为止没有成功。

1 个答案:

答案 0 :(得分:3)

假设案例类如case class Pet(animal: String, age: Int)

list.groupBy(_.animal).values.map(_.maxBy(_.age)).toList

对于List[BSONDocument],同样的概念:

list.groupBy(_.getAs[String]("animal")).values.map(_.maxBy(_.getAs[Int]("age"))).toList