1

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

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”类型。

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

4

2 回答 2

4

JSONDocumentJsObject与使用时相同JSONSerializationPack。使用隐式写入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)
}
于 2016-03-23T05:28:23.073 回答
1

例如,您想从https://docs.mongodb.com/v3.4/reference/operator/aggregation/subtract/#subtract-numbers执行示例,并使用“总”排序使用 play recitve 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
  }
}
于 2016-12-06T09:49:05.070 回答