如何在 Play Framework 中使用 ReactiveMongo + JSON 聚合框架? [英] How to use ReactiveMongo + JSON aggregation framework in Play Framework?

查看:25
本文介绍了如何在 Play Framework 中使用 ReactiveMongo + JSON 聚合框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 ReactiveMongo 来利用 MongoDB 的聚合框架.我只找到使用 BSON 的 这个例子.我想使用 JSON,所以我将代码更改为:

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)
}

但是没有JSONDocument"类型.

But there's no "JSONDocument" type.

完成这种方法的正确方法是什么?

What would be the correct way to finish this approach?

推荐答案

JSONDocument 与使用 JSONSerializationPack 时的 JsObject 相同.JsObject 使用隐式编写器转换为 JSONDocument.

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)
}

这篇关于如何在 Play Framework 中使用 ReactiveMongo + JSON 聚合框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆