How to insert document field value as ISODate with Ruby MongoDB driver? How to insert document field value as ISODate with Ruby MongoDB driver? mongodb mongodb

How to insert document field value as ISODate with Ruby MongoDB driver?


I couldn't find any documentation on this but if you look at the official examples, you'll see this:

result = client[:restaurants].insert_one({  #...  grades: [    {      date: DateTime.strptime('2014-10-01', '%Y-%m-%d'),      grade: 'A',      score: 11    },    #...  ]  #...})

That would suggest that you can use simple DateTime instances to insert times into MongoDB. So what happens if we try that? Well:

irb>  mongo[:pancakes].insert_one(:kind => 'blueberry', :created_at => DateTime.now)

and then in MongoDB:

> db.pancakes.find(){ "_id" : ..., "kind" : "blueberry", "created_at" : ISODate("2016-05-15T17:44:12.096Z") }

The ISODate that we want is there.

Then if we pretend we're in Rails:

irb> require 'active_support/all' # To get to_datetimeirb> mongo[:pancakes].insert_one(:kind => 'banana', :created_at => '2016-05-15T06:11:42.235Z'.to_datetime)

we get this inside MongoDB:

> db.pancakes.find(){ "_id" : ObjectId("5738b56cf638ccf407c71ef5"), "kind" : "blueberry", "created_at" : ISODate("2016-05-15T17:44:12.096Z") }{ "_id" : ObjectId("5738b74ef638ccf4da4c2675"), "kind" : "banana", "created_at" : ISODate("2016-05-15T06:11:42.235Z") }

ISODates again.

I'm using version 2.2.5 of the official Ruby driver here.