0

I'm trying to write a function that aggregates data from my MongoDB using ReactiveMongo (0.12), with Play JSON serialisation (similar to this question).

So this is what I have:

   def getPopAggregate(col: JSONCollection) = {

     import col.BatchCommands.AggregationFramework.{AggregationResult, Group, Match, SumField}
     col.aggregate(
       Group(JsString("$rstId"))("totalPopulation" -> SumField("population")),
       List(Match(Json.obj("totalPopulation" -> Json.obj("$gte" -> 1000))))
     ).map(_.firstBatch)

   }

This outputs Future[List[JsObject]], however I want to map the results to a List of my case class (i.e. Future[Seq[PopAggregate]]).

   case class PopAggregate(rstId: Option[BSONObjectID], totalPopulation: Double)

   object PopAggregate {
       implicit val popAggregateFormat = Json.format[PopAggregate]
   }

I hope someone can spare a moment to help me past this one. Many thanks!

cchantep
  • 9,118
  • 3
  • 30
  • 41
  • Having a look at the [documentation](http://reactivemongo.org/releases/0.12/documentation/advanced-topics/aggregation.html#places-examples), examples can be seen, such as one mapping aggregation result as `GeoPlace` (... `head[GeoPlace]`). – cchantep Sep 24 '17 at 19:06
  • @cchantep thanks. The thing is I'm using the *Play Framework JSON Library* which uses JSON rather than BSON - like the question that I linked to and the example that I gave. There is not much documentation using these. – jesus g_force Harris Sep 24 '17 at 19:14
  • Using JSON serialization doesn't change in any way the mechanism. Have you tried it before? – cchantep Sep 24 '17 at 19:19
  • This actually worked: `_.head[PopAggregate]` instead of `_.firstBatch` that is – jesus g_force Harris Sep 24 '17 at 19:40

0 Answers0