1 Reply Latest reply on Apr 8, 2015 2:14 AM by (Hector)

    MongoDB - Date insert

    (Hector)

      Has anyone experience with MongoDB and Coldfusion?

      I have problems to store a Date object correctly in MongoDB.

      I am using the Mongo-Java Driver.

        • 1. Re: MongoDB - Date insert
          (Hector) Level 1

          That is my code.

           

           

          <cfset utilDate = CreateObject("java","java.util.Date") />

          <cfset utilJSON = CreateObject("java", "com.mongodb.util.JSON") />

          <cfset SimpleDaxteFormat  = CreateObject("java", "java.text.SimpleDateFormat").init("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") />

          <cfset SimpleDateFormat2 = CreateObject("java", "java.text.SimpleDateFormat").init("yyyy-MM-dd'T'HH:mm:ss.SSS'+01:00'") />

          <cfset jodaIso = CreateObject("java", "org.joda.time.format.ISODateTimeFormat") />

           

          <cfset isoDate1 = "2015-03-25T15:23:57.000Z" />

          <cfset isoDate2 = "2015-03-25T15:23:57.000+01:00" />

          <cfset isoDate3 = "2015-03-25T15:23:57+01:00" />

           

          <!--- Joda Date-Time --->

          <cfset jMillis = jodaIso.dateTimeNoMillis() />

          <cfset jpdt = jMillis.parseDateTime(isoDate3) />

          <cfset jToDateIso = jpdt.toDateTimeISO() />

           

          <!--- Document data for insert : all three should be DATE Objects! --->

          <cfset doc = {

             "date1" = SimpleDateFormat.parse(isoDate1),

             "date2" = SimpleDateFormat2.parse(isoDate2),

             "date3" = jToDateIso.toDate()

          } />

           

          <!--- JSON parsing --->   

          <cfset doc = utilJSON.parse(SerializeJSON(doc)) />

          <cfset col.save(doc) />

           

           

          Listing Document in MongoClient:

           

          > db.datetest.find().pretty()

          {

              "_id" : ObjectId("5512c4fd1e106620a5b49dac"),

              "date1" : "März, 25 2015 15:23:57",

              "date2" : "März, 25 2015 15:23:57",

              "date3" : "März, 25 2015 15:23:57"

          }

           

          All three column fields are strings ;(

          The fields should be Date-Objects, output should be:

          "date1" : ISODate("2015-03-25 15:23:57"), ...