mongodb將字段從字符串轉到日期類型

直接上代碼:

# x.Age="Aug-11-2019 12:02:42 AM"; 日期字符串
db.myTable.find({Age:{$type:2}}).forEach(function(x){
    var myregexp = /(...)-(..)-(....) (..):(..):(..) (..)/;
    if(myregexp.test(x.Age)){
            var matches = myregexp.exec(x.Age);
            h_str=matches[4];
            if (matches[7]=="AM" && h_str=="12"){
                var h_str="00";
            };
            if (matches[7]=="PM" && matches[4]!="12"){
                var h_str=12+NumberInt(h_str);
            };
        };
    var timeStr=matches[1]+" "+matches[2]+" "+matches[3]+" "+h_str+":"+matches[5]+":"+matches[6];
    x.Age=new Date(timeStr);
    db.myTable.save(x);
})

$type是mongodb的數據類型:

類型 對應數字 別名 說明
Double 1 double  
String 2 string  
Object 3 object  
Array 4 array  
Binary data 5 binData  
Undefined 6 undefined 棄用
ObjectId 7 objectId  
Boolean 8 “bool”  
Date 9 “date”  
Null 10 “null”  
Regular Expression 11 “regex”  
DBPointer 12 “dbPointer”  
JavaScript 13 “javascript”  
Symbol 14 “symbol”  
JavaScript(with scope) 15 “javascriptWithScope”  
32-bit integer 16 “int”  
Timestamp 17 “timestamp”  
64-bit integer 18 “long”  
Min key -1 “minKey”  
Max key 127 “maxKey”  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章