Reputation: 1496
I have the following 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}
]
How do I return a result so that I get both dogs, cats and rabbits with the max age. Example:
[
{ "animal": "dog", "age": 3}, # oldest dog in DB
{ "animal": "cat", "age": 4}, # oldest cat in DB
{ "animal": "rabbit", "age": 9} # oldest rabbit in DB
]
I am trying to get this using two scala .map() aggregation but no success so far.
Upvotes: 2
Views: 2200
Reputation: 6182
Assuming a case class like case class Pet(animal: String, age: Int)
:
list.groupBy(_.animal).values.map(_.maxBy(_.age)).toList
For List[BSONDocument]
, same concept:
list.groupBy(_.getAs[String]("animal")).values.map(_.maxBy(_.getAs[Int]("age"))).toList
Upvotes: 4