0

我是使用 scala 和 reactivemongo 的 Play framework 2.3 的新手。我已经开发了几个页面来将表单中的数据加载到 mongodb 中。

到目前为止,一切都很好。但是现在我打算使用 mongodb 的嵌套文档功能,因为 mongodb 中没有对 JOINS 的直接支持。我知道手动参考和数据库参考方式加入 MongoDB 中的集合。

在这个论坛上发布了一些与 mongodb 中的嵌套文档相关的问题,但它们对我没有帮助。

如果您能告诉我,如何使用 play framework、scala 和 reactivemongo 在 mongodb 集合中的现有文档中插入更新子文档,我将不胜感激?

数据结构如下:

   "_id" : ObjectId("5516ae699aaebdfc0bc47f7d"),
   "name" : "ABCD",
   "address" : "Blue Skies",
   "dob" : 135962900000,
   "email" : ""

我想添加新的子文档条目,如下所示:

   "_id" : ObjectId("5516ae699aaebdfc0bc47f7d"),
   "name" : "ABCD",
   "address" : "Blue Skies",
   "dob" : 01/01/1970,
   "email" : "",
      “visits” : [
    { 
        “date” : 18/02/2015,
        “comments” : “Some comments”,
        “createdBy” : “XYZ”
    },
    { 
        “date” : 23/03/2015,
        “comments” : “Some comments”,
        “createdBy” : “PQR” 
      }
     ]

这是我更新集合中文档的代码的样子:

def updateData(id: String) = Action.async { implicit request =>
projectForm.bindFromRequest.fold(
  formWithErrors => Future.successful(BadRequest(html.editProject(id, formWithErrors))),
  project => {
    val futureUpdateProj = collection.update(Json.obj("_id" -> Json.obj("$oid" -> id)), project.copy(_id = BSONObjectID(id)))
    futureUpdateProj.map { result =>
      projectsHome.flashing("success" -> s"Project ${project.name} has been updated")
    }.recover {
      case t: TimeoutException =>
        Logger.error("Problem found in Project update process")
        InternalServerError(t.getMessage)
    }
  })
  }
4

0 回答 0