Convert String to date or ISODate using Mongo Shell in MongoDB

时间:2017-04-10 00:55:50

标签: mongodb

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 个答案:

答案 0 :(得分:0)

这是使用“01-JUN-2009 00:00”作为日期值的一种方法。

首先,解析出时间值:

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" }
]);

然后,将月份MMM字符串转换为MM数字,就像您在评论中提到的那样。 您需要使用版本3.4或更高版本才能使用switch语句:

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" }
]);

然后,您可以创建MongoDB将其解释为日期的字符串:

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}});
});

最后一步是通过将字符串传递给Date():

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