天天看點

Mongo修改資料類型

引言

本文主要講解Mongodb的類型轉換。包括:string轉double, string轉int, string轉Date。

0. 出現類型不一緻的原因

ES導入資料到Mongo後,會出現類型統一改為String的問題。

傳統關系型資料庫,在設計表處,右鍵就可以完成修改表類型。

但是非關系型資料庫,沒有這種實作。隻有通過指令行操作實作。

驗證表明,可以通過如下的接口進行修改。

1、Mongodb類型轉換接口

//string轉為double類型
db.law.find().forEach( function (x) {
  x.state = parseInt(x.state);
  db.law.save(x);
});

//string轉為int類型
db.law.find().forEach( function (x) {
  x.ise= NumberInt (x.ise);
  db.law.save(x);
});

//string轉化為date類型
db.law.find().forEach( function (x) {
 x.eift = new ISODate(x.eift);
  db.law.save(x);
});           

2、類型轉換一鍵腳本實作

[root@Node-C6 mongo_process]# cat ./mongo_uopdate.sh

#!/bin/sh
mongo data <<\EOF
db.law.find().forEach( function (x) {
  x.state = parseInt(x.state);
  x.id= NumberInt(x.id);
 x.eift = new ISODate(x.eift);
 x.ctime = new ISODate(x.ctime );
 x.pt= new ISODate(x.pt);
  db.law.save(x);
});
EOF           

3、執行成功标記

[root@Node-C6 mongo_process]# ./mongo_uopdate.sh
MongoDB shell version: 3.2.7
connecting to: data
bye           

參考:

https://glassonionblog.wordpress.com/2014/05/15/mongodb-changing-column-names-and-column-types/

作者:銘毅天下

轉載請标明出處,原文位址:

http://blog.csdn.net/laoyang360/article/details/72594344