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

Execute raw commands in a MongoDb collection from Play 2 using ReactiveMongo and JSONCollection

您好,我正在使用 ReactiveMongo 和 Play,我希望能够在 collection.

中 运行 MongoDB 命令

我的 collection 是这样声明的:

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

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

关于 raw 命令的文档是 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]
}