Mongodb Document to Scala案例类

时间:2018-05-09 07:24:48

标签: mongodb scala document

我正在使用MongoDB scala驱动程序。我从MongoDB获取记录时遇到问题。 以下是我的MongoDB初始化

private val client: MongoClient = MongoClient()
private val database: MongoDatabase = client.getDatabase(“rulemgntdb”)
val WorkOrdercollection: MongoCollection[Document] = database.getCollection("workOrder")

查询查询:

MongoFactory.WorkOrdercollection.find().collect().subscribe(
     (results: Seq[Document]) =>
           println(s”Found: #${results}“)

   ) 

结果印刷如下:

Found: #List(Document((_id,BsonString{value=‘5af153f49547a205f9798129’}), (workOrderId,BsonString{value=‘9a9e1ce8-c576-4a15-a1ff-4af780b14b7f’}), (thingId,BsonString{value=‘Mumbai_Robot_3’}), (alertId,BsonString{value=‘Alert_1’}), (description,BsonString{value=‘Robot is not in good condition’}), (lastViewedDate,BsonDateTime{value=1525781377952}), (suggestedMaintenanceDate,BsonDateTime{value=1525781377952}), (startDate,BsonDateTime{value=1525781377952})))

我想将此文档映射到我的Case类。

案例类如下:

case class WorkOrder (
           var  id  : String = (new ObjectId()).toString(),
           var  workOrderId: String,
           var  thingId  : String,
           var  alertId : String,
           var  description  : String,
            val lastViewedDate : Date,
            val suggestedMaintenanceDate : Date,
            val startDate : Date
    )

如果我从Document获取JSON字符串,请执行以下操作:

MongoFactory.WorkOrdercollection.find(query).subscribe(
  (user: Document) => println(user.toJson()),                         // onNext
  (error: Throwable) => println(s"Query failed: ${error.getMessage}"), // onError
  () => println("Done")                                               // onComplete
)

然后我会得到以下JSON字符串:

{ “_id” : “5af153f49547a205f9798129", “workOrderId” : “9a9e1ce8-c576-4a15-a1ff-4af780b14b7f”, “thingId” : “Mumbai_Robot_3", “alertId” : “Alert_1", “description” : “Robot is not in good condition”,  “lastViewedDate” : { “$date” : 1525781377952 }, “suggestedMaintenanceDate” : { “$date” : 1525781377952 }, “startDate” : { “$date” : 1525781377952 } }

我可以将JSON字符串解析为case类但是......看看“startDate” : { “$date” : 1525781377952 }我无法将MongoDB日期解析为scala日期

如何将Document映射到Case类?

2 个答案:

答案 0 :(得分:1)

您需要为$date字段提供自定义编解码器。以下显示了如何在play-json中完成,但概念在其他JSON库中类似:

object WorkOrder {
  implicit val dateRead: Reads[Date] =
    (__ \ "$date").read[Long].map(date => new Date(date))

  implicit val dateWrite: Writes[Date] = new Writes[Date] {
    def writes(date: Date): JsValue = Json.obj("$date" -> date.getTime)
  }

  implicit val codec = Json.format[WorkOrder]
}

答案 1 :(得分:0)

您可以使用JSON库。

play-json

case class WorkOrder (
  id: String,
  workOrderId: String,
  thingId: String,
  alertId: String,
  description: String,
  lastViewedDate: Date,
  suggestedMaintenanceDate: Date,
  startDate: Date
)

object WorkOrder {
  implicit lazy val fmt = Json.format[WorkOrder]
}

def documentToWorkOrder(doc: Document): WorkOrder = {
  Json.parse(user.toJson().toString).validate[WorkOrder] match {
    case JsSuccess(_, workOrderObj) => workOrderObj
    case JsError(throwable)  => throw throwable
  }
}

//then in your code
MongoFactory.WorkOrdercollection.find(query).subscribe(
 (user: Document) => documentToWorkOrder(user),
 (error: Throwable) => println(s"Query failed: ${error.getMessage}"),
 () => println("Done")
)