Mongodb Document to Scala case class

2020-03-30 01:59发布

问题:

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?

回答1:

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


回答2:

You could use a JSON library.

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