Mongodb文档到Scala案例类 [英] Mongodb Document to Scala case class
问题描述
我正在使用MongoDB scala驱动程序.我从MongoDB获取记录时遇到问题. 以下是我的MongoDB初始化
I am using MongoDB scala driver. I have a problem with fetching record from MongoDB. Following is my MongoDB initialization
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类.
I want to map this Document to my Case class.
案例类如下:
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字符串:
If I do following for getting JSON string from Document :
MongoFactory.WorkOrdercollection.find(query).subscribe(
(user: Document) => println(user.toJson()), // onNext
(error: Throwable) => println(s"Query failed: ${error.getMessage}"), // onError
() => println("Done") // onComplete
)
然后我将获得以下JSON字符串:
Then I will get Following JSON String:
{ "_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 Date解析为scala Date
I can Parse JSON string to case class but...Look at "startDate" : { "$date" : 1525781377952 }
I am not able to Parse MongoDB Date to scala Date
如何将Document映射到Case类?
How can I map Document to Case class?
推荐答案
您需要为$date
字段提供自定义编解码器.下面显示了如何在play-json
中完成此操作,但是在其他JSON库中该概念相似:
You need to provide a custom codec for $date
field. The following shows how it is done in play-json
but the concept is similar in other JSON libraries:
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]
}
这篇关于Mongodb文档到Scala案例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!