summerNight summerNight - 1 year ago 114
Scala Question

Scala filter a list based on a max value

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.

Answer Source

Assuming a case class like case class Pet(animal: String, age: Int):


For List[BSONDocument], same concept: