如何在Play Framework中使用ReactiveMongo + JSON聚合框架?

时间:2016-03-22 21:36:38

标签: playframework reactivemongo play-reactivemongo

我需要使用ReactiveMongo来利用MongoDB的聚合框架。我只找到使用BSON的this example。我想使用JSON,所以我将代码更改为:

lr_pipeline = Pipeline([('clf', LogisticRegression())])
lr_parameters = {}

lr_gs = GridSearchCV(lr_pipeline, lr_parameters, n_jobs=-1)
lr_gs = lr_gs.fit(X,y)

print lr_gs.confusion_matrix # Would like to be able to do this

但是没有“JSONDocument”类型。

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

2 个答案:

答案 0 :(得分:4)

使用JSONDocument时,

JsObjectJSONSerializationPack相同。 JsObject使用隐式作者转换为JSONDocument

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

答案 1 :(得分:1)

例如,您希望从https://docs.mongodb.com/v3.4/reference/operator/aggregation/subtract/#subtract-numbers执行带有'total'排序的示例 使用play reitve mongo 0.12.0它应该看起来像

// don't forget to import this !!
import reactivemongo.play.json.commands.JSONAggregationFramework._

def salesDb = reactiveMongoApi.database.map(_.collection[JSONcollection]("sales"))

val result = salesDb.flatMap { collection =>
  val projectOperator = Project(
    Json.obj(
        "item" -> 1,
        "total" -> Json.obj("$subtract" -> JsArray(Seq(Json.obj("$add" -> Seq("$price", "$fee")), JsString("$discount"))))
    )
  )
  val sortOperator = Sort(Ascending("total"))
  collection.aggregate(firstOperator = projectOperator, otherOperators = List(sortOperator)).map { agregationResult =>
    agregationResult.firstBatch
  }
}