Search code examples
playframeworkreactivemongoplay-reactivemongo

How to use ReactiveMongo + JSON aggregation framework in Play Framework?


I need to utilize MongoDB's aggregation framework using ReactiveMongo. I only find this example which uses BSON. I would like to use JSON so I changed the code to :

def populatedStates(col: JSONCollection) = {
  import col.BatchCommands.AggregationFramework.{AggregationResult, Group, Match, SumField}
  val res: Future[AggregationResult] = col.aggregate(
    Group(JsString("$state"))("totalPop" -> SumField("population")),
    List(Match(JSONDocument("totalPop" -> JSONDocument("$gte" -> 10000000L)))))
  res.map(_.firstBatch)
}

But there's no "JSONDocument" type.

What would be the correct way to finish this approach?


Solution

  • JSONDocument is the same as JsObject when you use JSONSerializationPack. JsObject converts to JSONDocument with implicit writer.

    import play.api.libs.json._
    import reactivemongo.play.json._
    import reactivemongo.play.json.collection.JSONCollection
    
    import scala.concurrent.Future
    
    def populatedStates(col: JSONCollection) = {
      import col.BatchCommands.AggregationFramework.{AggregationResult, Group, Match, SumField}
      val res: Future[AggregationResult] = col.aggregate(
        Group(JsString("$state"))("totalPop" -> SumField("population")),
        List(Match(Json.obj("totalPop" -> Json.obj("$gte" -> 10000000L)))))
      res.map(_.firstBatch)
    }