1. 程式人生 > >修改MongDB的數據類型

修改MongDB的數據類型

clas string類型 進制 布爾值 存儲 foreach -418 num spa

語法:

db.集合.find({"列":{$type:2}}).forEach(function(x){

x.列=parseFloat(x.列);db.order.save(x)

})

db.order.find({"saleprice":{$type:2}}).forEach(function(x){x.saleprice=parseFloat(x.saleprice);db.order.save(x)})

( find().裏為數據對應的類型,2表示str。也可以不寫 )

技術分享圖片

mongoDB的數據類型

Object ID :文檔的id

String: 字符串,最常用,必須是utf-8

Boolean:布爾值,true 或者false

Integer:整數

Double:浮點數

Arrays:數組或者列表,多個值存儲到一個鍵

Object:用於嵌入文檔,即一個值為一個文檔

Null:存儲null值

Timestamp:時間戳

Date:存儲當前日期或時間unix時間格式

Object ID:

  每個文檔都有一個屬性,為_id保證文檔的唯一性;

  可以自己去設置_id插入文檔

  如果自己沒設置,mongoDB為每個文檔提供一個獨特的_id ,是一個12字節十六進制數

      前4個字節為當前時間戳

      接下來的3個字節為機器ID

      接下來2個字節為mongo的服務進程ID

      最後3個是簡單的增量值

常見的轉化

技術分享圖片
db.getCollection(‘bond_sentiment_bulletin‘).find({‘pubDate‘: {$type:2}}).forEach(
    function(doc){
        db.getCollection(‘bond_sentiment_bulletin‘).update({‘_id‘: doc._id},{$set:{‘pubDate‘: new ISODate(doc.pubDate)}})
    }
)
or 
db.getCollection(
‘bond_sentiment_bulletin‘).find({‘pubDate‘: {$type:2}}).forEach( function(doc){ doc.pubDate = new ISODate(doc.pubDate); db.getCollection(‘bond_sentiment_bulletin‘).save(doc); } )
更改String類型為Date類型 技術分享圖片
db.getCollection(‘bond_sentiment_bulletin‘).find({"_id" : 416,‘pubDate‘:{$type:9}}).forEach( 
    function(x){ 
        x.pubDate = x.pubDate.toISOString(); 
        db.getCollection(‘bond_sentiment_bulletin‘).save(x); 
    } 
)
更改Date類型為String類型 技術分享圖片
db.getCollection(‘bond_sentiment_bulletin‘).find({"_id" : 419}).forEach( 
    function(x){ 
        x.status = String(x.status); 
        db.getCollection(‘bond_sentiment_bulletin‘).save(x); 
    } 
)
將類型轉為str 技術分享圖片
db.getCollection(‘bond_sentiment_bulletin‘).find({"_id" : 419,‘pubDate‘:{$type:9}}).forEach( 
    function(x){ 
        x.pubDate = NumberLong(x.pubDate.getTime()/1000); 
        db.getCollection(‘bond_sentiment_bulletin‘).save(x); 
    } 
)
把時間類型轉為NumberLong的時間戳類型 技術分享圖片
db.getCollection(‘bond_sentiment_bulletin‘).find({‘sentiment‘ : { $type : 1 }}).forEach(
    function(x) {  
        x.sentiment = NumberInt(x.sentiment);
        db.getCollection(‘bond_sentiment_bulletin‘).save(x);  
    }
)
修改double類型為int類型 技術分享圖片
db.getCollection(‘bond_sentiment_bulletin‘).find({‘editTime‘: {$type:2}}).forEach(
    function(doc){
        db.getCollection(‘bond_sentiment_bulletin‘).update({‘_id‘: doc._id},{$set:{‘editTime‘: parseFloat(doc.editTime)}})
    }
)
字符串轉為浮點數 技術分享圖片
db.getCollection(‘bond_sentiment_bulletin‘).find({‘editTime‘: {$type:2}}).forEach(
    function(doc){
        db.getCollection(‘bond_sentiment_bulletin‘).update({‘_id‘: doc._id},{$set:{‘editTime‘: parseInt(doc.editTime)}})
    }
)
字符串轉為double

參考:

https://blog.csdn.net/xc_zhou/article/details/86644144

修改MongDB的數據類型