使用ReactiveMongo和JSONCollection在Play 2的MongoDb集合中执行原始命令

时间:2016-09-13 14:47:17

标签: mongodb reactivemongo play-reactivemongo

您好我正在使用ReactiveMongo和Play,我希望能够在集合中运行MongoDB命令。

我的收藏是这样宣布的:

def thingsJSONCollection : Future[JSONCollection] =
  database.map( connectedDb => 
    connectedDb.collection[JSONCollection]("thingsCollection")
  )

我想执行的命令声明如下:

val commandDocument = Json.obj(
    "geoNear" -> "thingsCollection",
    "near" -> Json.obj(
      "type" -> "Point",
      "coordinates" -> Seq(lon, lat)),
    "spherical" -> true,
    "minDistance" -> 0,
    "maxDistance" -> 5000
  )

最后,这是不编译的代码:

thingsJSONCollection.map{
  collection => collection.runCommand( commandDocument )
}

当我尝试执行命令时,我收到一条很长的错误消息,基本上说runCommand不接受JsObject作为参数:

Error:(618, 57) overloaded method value runCommand with alternatives:
  [C <: reactivemongo.api.commands.CollectionCommand](command: C)(implicit writer: collection.pack.Writer[reactivemongo.api.commands.ResolvedCollectionCommand[C]])reactivemongo.api.commands.CursorFetcher[collection.pack.type,reactivemongo.api.Cursor] <and>
  [R, C <: reactivemongo.api.commands.CollectionCommand with reactivemongo.api.commands.CommandWithResult[R]](command: C with reactivemongo.api.commands.CommandWithResult[R])(implicit writer: collection.pack.Writer[reactivemongo.api.commands.ResolvedCollectionCommand[C]], implicit reader: collection.pack.Reader[R], implicit ec: scala.concurrent.ExecutionContext)scala.concurrent.Future[R]
 cannot be applied to (play.api.libs.json.JsObject)
  thingsJSONCollection.map(collection => collection.runCommand(commandDocument))
                                                    ^

有人可以帮我找到在Play中使用ReactiveMongo在MongoDB集合中执行原始命令的方法吗?

1 个答案:

答案 0 :(得分:1)

有关原始命令的文档是available online,用于BSON序列化。 它可以适用于JSON序列化。

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

import play.api.libs.json.{ JsObject, Json }

import reactivemongo.play.json._
import reactivemongo.api.commands.Command

def rawResult(db: reactivemongo.api.DefaultDB): Future[JsObject] = {
  val commandDoc = Json.obj(
    "aggregate" -> "orders", // we aggregate on collection `orders`
    "pipeline" -> List(
      Json.obj("$match" -> Json.obj("status" -> "A")),
      Json.obj(
        "$group" -> Json.obj(
          "_id" -> "$cust_id",
          "total" -> Json.obj("$sum" -> "$amount"))),
      Json.obj("$sort" -> Json.obj("total" -> -1))
    )
  )
  val runner = Command.run(JSONSerializationPack)

  runner.apply(db, runner.rawCommand(commandDoc)).one[JsObject]
}