首先,可以使用reactivemongo将模型类序列化为BSON。查看文档以了解如何操作。
如果你想
BSONDocument
从…起
String
通过play json,您可以使用
val playJson: JsValue = Json.parse(jsonString)
val bson: BSONDocument = play.modules.reactivemongo.json.BSONFormats.reads(playJson).get
编辑
我在这里的文档中找到了更多:
http://reactivemongo.org/releases/0.11/documentation/tutorial/play2.html
你可以导入这两个
import reactivemongo.play.json._
import play.modules.reactivemongo.json.collection._
而不是使用默认的Collection实现(它与
BSON结构+BSONReader/BSONWriter),我们使用
与JsObject+读/写一起工作的实现。
所以您可以创建这样的专门集合(必须是
def
不
val
):
def collection: JSONCollection = db.collection[JSONCollection]("persons")
从现在起,您可以将其用于play-json,而不是BSON,所以只需传入
Json.parse(jsonString)
作为要插入的文档应该有效。您可以在链接中看到更多示例。
编辑2
我得到了要编译的代码:
组件控制器
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.json._
import play.modules.reactivemongo.json.collection.{JSONCollection, _}
import reactivemongo.api.MongoDriver
import reactivemongo.play.json._
import play.api.libs.json.Reads._
import scala.util.{Failure, Success}
object Mongo {
def collection: JSONCollection = {
val driver = new MongoDriver
val connection = driver.connection(List("localhost"))
val db = connection("superman")
db.collection[JSONCollection]("IncomingRequests")
}
def writeDocument() = {
val jsonString = """{
| "guid": "alkshdlkasjd-ioqweuoiquew-123132",
| "title": "Hello-2016",
| "year": 2016,
| "action": "POST",
| "start": "2016-12-20",
| "stop": "2016-12-30"}"""
val document = Json.parse(jsonString).as[JsObject]
val future = collection.insert(document)
future.onComplete {
case Failure(e) => throw e
case Success(result) =>
println("successfully inserted document with result = " + result)
}
}
}
重要的是
import play.api.libs.json.Reads._
你需要
JsObject
,不只是任何
JsValue
val document = Json.parse(jsonString).as[JsObject]