Reputation: 952
Hi I am using ReactiveMongo and Play, and I would like to be able to run a MongoDB command in a collection.
My collection is declared like that :
def thingsJSONCollection : Future[JSONCollection] =
database.map( connectedDb =>
connectedDb.collection[JSONCollection]("thingsCollection")
)
The command I would like to execute is declared like that :
val commandDocument = Json.obj(
"geoNear" -> "thingsCollection",
"near" -> Json.obj(
"type" -> "Point",
"coordinates" -> Seq(lon, lat)),
"spherical" -> true,
"minDistance" -> 0,
"maxDistance" -> 5000
)
And finally, here is the code that does not compile :
thingsJSONCollection.map{
collection => collection.runCommand( commandDocument )
}
When I try to execute the command, I get a long error message that basically says that runCommand
does not accept JsObject
as argument :
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))
^
Could someone help me find the way to execute raw commands in a MongoDB collection from Play using ReactiveMongo, please?
Upvotes: 0
Views: 774
Reputation: 9168
The documentation about raw command is available online for the BSON serialization. It can be adapted for the JSON serialization.
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]
}
Upvotes: 1