简体   繁体   English

如何获取要作为日期存储在MongoDB中而不是Int64的日期?

[英]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. 我正在使用新的MongoDB Scala驱动程序。 When I store a java.util.Date, it is being stored in MongoDB as an Int64 instead of a MongoDB Date. 当我存储java.util.Date时,它作为Int64而不是MongoDB日期存储在MongoDB中。 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. 但是在MongoDB中最终是Int64,而不是日期。 How do I get a Date into MongoDB? 如何获取日期到MongoDB?

If you are using the latest MongoDB Scala Driver v1.1 . 如果您使用的是最新的MongoDB Scala驱动程序v1.1 Instead of using the Json.obj to build your document, try using Document class. 与其尝试使用Json.obj来构建文档,不如尝试使用Document类。

The BsonTransformer will transform java.util.Date to BsonDateTime BsonTransformer会将java.util.Date转换为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. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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