简体   繁体   中英

How do I get a Date to store as a Date in MongoDB instead of an Int64?

I'm using the new MongoDB Scala Driver. When I store a java.util.Date, it is being stored in MongoDB as an Int64 instead of a MongoDB Date. I have some code that looks like this:

implicit val writer = new Writes[Forecast] {
  def writes(x: Forecast): JsValue = {
    Json.obj(
      // ...
      "issueDateTime" -> x.issueDateTime // which is a java.util.Date
      // ...
    )
  }
}

but what ends up in MongoDB is an Int64, not a Date. How do I get a Date into MongoDB?

If you are using the latest MongoDB Scala Driver v1.1 . Instead of using the Json.obj to build your document, try using Document class.

The BsonTransformer will transform java.util.Date to BsonDateTime

For example:

val newdate = new Date()
val doc: Document = Document("test" -> newdate)
collection.insertOne(doc).results()

Will result in :

{  "_id" : ObjectId("56665bf619a63d9e538b2851"), 
    "test" : ISODate("2015-12-08T04:26:29.999Z") 
}

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM