1
votes

I have thousands of objects in MongoDB. And I have a field called "Insert_Date" which String format:"DD-Month(eg.JUN)-YYYY hh:mm". I would like to convert it to Date or ISODate using mongo shell I've tried this one but it showed error "invalid ISO date"

db.collection.find().forEach(function(doc) { 
doc.Insert_Date=new ISODate(doc.Insert_Date);
db.collection.save(doc); 
})

Is there another way to convert it may be using regex? Any help would be appriciated.

1

1 Answers

1
votes

Here's one way to do it using "01-JUN-2009 00:00" as the date value.

First, parse out the time values:

db.dates.aggregate([
   {
    $project : {
        day: { $substr: [ "$Date_Time", 0, 2 ] },
        month: { $substr: [ "$Date_Time", 3, 3 ] },
        year: { $substr: [ "$Date_Time", 7, 4 ] },
        hour: { $substr: [ "$Date_Time", 12, 2 ] },
        minute: { $substr: [ "$Date_Time", 15, 2 ] }
        }
    },
    { $out : "dates" }
]);

Then, convert the month MMM string to MM numeric like you've mentioned in the comment. You will need to be on version 3.4 or higher to use the switch statement:

db.dates.aggregate( [
  {
    $project: {
        "day": "$day",
        "year": "$year",
        "hour": "$hour",
        "minute": "$minute",
        "month" :
        {
            $switch: { 
                branches: [
                    { case: { $eq: [ "$month", "JAN" ] }, then: "01" },
                    { case: { $eq: [ "$month", "FEB" ] }, then: "02" },
                    { case: { $eq: [ "$month", "MAR" ] }, then: "03" },
                    { case: { $eq: [ "$month", "APR" ] }, then: "04" },
                    { case: { $eq: [ "$month", "MAY" ] }, then: "05" },
                    { case: { $eq: [ "$month", "JUN" ] }, then: "06" },
                    { case: { $eq: [ "$month", "JUL" ] }, then: "07" },
                    { case: { $eq: [ "$month", "AUG" ] }, then: "08" },
                    { case: { $eq: [ "$month", "SEP" ] }, then: "09" },
                    { case: { $eq: [ "$month", "OCT" ] }, then: "10" },
                    { case: { $eq: [ "$month", "NOV" ] }, then: "11" },
                    { case: { $eq: [ "$month", "DEC" ] }, then: "12" }
                ]
            }
        }
      }
   },
   { $out : "dates" }
]);

Then, you can create the string that MongoDB will interpret as a date:

db.dates.find().forEach(function(doc) { 
    db.dates.update({_id: doc._id},{$set : {"Date_Time": doc.year + '-' + doc.month + '-' + doc.day + 'T' + doc.hour + ':' + doc.minute}});
});

The last step is to construct an ISODate by passing the string into Date():

db.dates.find().forEach(function(doc) { 
    doc.Date_Time=new Date(doc.Date_Time);
    db.dates.save(doc); 
})