json操作并推送到mongodb(PLAY-2.7-Scala-2.12)

时间:2019-02-15 13:20:23

标签: json mongodb scala playframework

任何人都可以帮助我将模型(例如用户(名称:字符串))转换 JSON 将其保存到MongoDB ??

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情。

Build.sbt:

"org.mongodb.scala" %% "mongo-scala-driver" % "2.6.0"
"com.typesafe.play" %% "play-json" % "2.7.1"

首先创建mongoDB配置。

val credential: MongoCredential = ???
val settings: MongoClientSettings = ???
val client: MongoClient = MongoClient(settings)
val db: MongoDatabase = client.getDatabase("db-name")
val collection: MongoCollection[Document] = client.getCollection("collection-name")

case class Model(name: string)

object Model {
    implicit val modelFormat: Format[Model] = Json.format[Model]
}

用法:

val data: JsValue = Json.toJson(new Model("Rex"))

插入db并检查是否插入了:) ..

collection.insertOne(Document(data.toString))