How to store date in MongoDB in ISO format instead of Long [Play, Scala and ReactiveMongo]?

2.3k views Asked by At

I'm trying to insert date in MongoDB using following way:

collection.insert(Json.obj("user"->"abc", "joined_date" -> DateTime.now))

In database:

   {                                                       
            "_id" : ObjectId("5865d99718969bca6a09450f"),   
            "user" : "abc",                                 
            "joined_date" : NumberLong("1483069847066")     
    }  

The problem here is that date is stored in database in Long millisec format but what I want is it to store in ISO Date format.

I have tried in MongoShell persisting the same data db.example.insert({user:"abc", joined_date:new Date()}) and the result is below:

{
        "_id" : ObjectId("5865d838a4f98c5bb83b1eb8"),
        "user" : "abc",
        "joined_date" : ISODate("2016-12-30T03:44:56.824Z")
}

So, how can I store date in ISODate format in database using ReactiveMongo?

1

There are 1 answers

0
cchantep On BEST ANSWER

You are using Play JSON to represent MongoDB document (not BSON), and the date is a Joda one converted as JSON number according the Play JSON module.

You can directly use BSON with the driver, and pass the date as BSONDateTime.

BSONDocument("myDate" -> BSONDateTime(..))

Or (assuming a ReactiveMongo version >= 0.11.9) you can use MongoDB JSON extended representation $date: date_value :

Json.obj("myDate" -> Json.obj("$date" -> dateTimeLong))

The JSON formats supported by the ReactiveMongo serialisation are documented.