1. 程式人生 > >mongo 批量轉換欄位型別的方法

mongo 批量轉換欄位型別的方法

引:由於專案前期開發的人沒規劃好,導致功能上業務邏輯的阻塞,現記錄下mongo如何批量轉換資料型別

函式解析

1.要先查詢出需要修改的欄位型別,不然直接轉換,如果資料表比較混亂,會導致轉換報錯

2.print 可以在mongo shell中 輸出引數

$type 有效的型別值,如下:


Type Number Alias Notes
Double 1 “double”
String 2 “string”
Object 3 “object”
Array 4 “array”
Binary data 5 “binData”
Undefined 6 “undefined” Deprecated.
ObjectId 7 “objectId”
Boolean 8 “bool”
Date 9 “date”
Null 10 “null”
Regular Expression 11 “regex”
DBPointer 12 “dbPointer” Deprecated.
JavaScript 13 “javascript”
Symbol 14 “symbol” Deprecated.
JavaScript (with scope) 15 “javascriptWithScope”
32-bit integer 16 “int”
Timestamp 17 “timestamp”
64-bit integer 18 “long”
Decimal128 19 “decimal” New in version 3.4.
Min key -1 “minKey”
Max key 127 “maxKey”

好了,接下來進行轉換的一步

//string轉為double型別

db.order.find({userID:{$type:"string"}}).forEach( function (x) {

 print( "user: " + x.userID );

 x.userID = parseInt(x.userID);

  db.order.save(x);

});

//string轉為int型別

db.order.find({userID:{$type:"string"}}).forEach( function (x) {

 print( "user: " + x.userID );

 x.userID = NumberInt(x.userID);

  db.order.save(x);

});


//string轉化為date型別

db.order.find({userID:{$type:"string"}}).forEach( function (x) {

 print( "user: " + x.userID );

 x.userID = new ISODate(x.userID);

  db.order.save(x);

});


//string轉化為obj型別

db.order.find({userID:{$type:"string"}}).forEach( function (x) {

 print( "user: " + x.userID );

 x.userID = ObjectId(x.userID);

  db.order.save(x);

});

type 型別 - 官網參考: https://docs.mongodb.com/manual/reference/operator/query/type/index.html