Unable to convert string(date) to ISODate in mongoDB 3.4

928 views
Skip to first unread message

devendra chauhan

unread,
Feb 1, 2018, 4:22:36 PM2/1/18
to mongodb-user
Unable to convert string to ISODate in mongoDB 3.4

My string is  : "update_date" : "3/20/2016 10:09:08 PM", 

db.testcollect.insertOne(
    "_id" : "blyCUz9kLbAgKWVE2G/tMg==", 
    "is_active" : NumberLong(0), 
    "insert_by" : "DCTEST", 
    "insert_date" : "3/20/2016 10:09:08 PM", 
    "update_by" : "DCTEST1", 
    "update_date" : "3/20/2016 10:09:08 PM", 
    "mdb_update_date" : ISODate("2018-02-01T09:42:23.190+0000")
});

In Logic 1 for conversion getting error "[main] Error: invalid ISO date :"

db.testcollect.find().forEach( function (x) { 
    x.update_date = ISODate(x.update_date);
        db.testcollect.save(x);
});

In Logic 2 for conversion getting error "Unrecognized expression '$dateFromString" because of mongodb lower version(I cannot upgrade to 3.6 as of now)

db.testcollect.aggregate( [ {
   $project: {
      date: {
         $dateFromString: {
            dateString: '$update_date',
            timezone: 'America/New_York'
         }
      }
   }
} ] );

Wan Bachtiar

unread,
Mar 7, 2018, 11:43:07 PM3/7/18
to mongodb-user

for conversion getting error “[main] Error: invalid ISO date :”

Hi Devendra,

Are you performing these commands on the mongo shell ?
ISODate() is only a mongo shell wrapper/helper to the Date` object.

In mongo shell, as an example you could do something as below:

let mydate = new Date("3/20/2016 10:09:08 PM").toISOString(); 
db.testcollect.insertOne({'foo':ISODate(mydate)});

Resulting in:

{
  "_id": ObjectId("5aa0bd58fbaeb86dc1fa5da6"),
  "foo": ISODate("2016-03-20T11:09:08Z")
}

You may also find Date Examples useful.

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages