scala连接mongodb_Mongodb文档到Scala案例类

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")

Find query :

MongoFactory.WorkOrdercollection.find().collect().subscribe(

(results: Seq[Document]) =>

println(s”Found: #${results}“)

)

Results printed like this :

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})))

I want to map this Document to my Case class.

Case class is like :

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

)

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

)

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 } }

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

How can I map Document to Case class?

解决方案

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]

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值