Mongodb中的mongoexport工具可以把一個collection導出成JSON格式或CSV格式的文件。MySQL支持導出CSV格式的數據以至於可以把MySQL的數據遷移至MongoDB中。
實踐演示:
mysql開啓安全路徑
vim /etc/my.cnf 添加以下配置
secure-file-priv=
重啓數據庫生效
/etc/init.d/mysqld restart
導出book庫下所有表
SELECT CONCAT(“select * from “,table_schema,”.”,table_name,
" into outfile ‘/bak/",table_schema,".",table_name,".csv’ fields terminated by ‘,’
optionally enclosed by ‘""’ escaped by ‘""’
lines terminated by ‘\r\n’;")
FROM information_schema.tables WHERE table_schema =‘book’;
不加雙引號
SELECT CONCAT(“select * from “,table_schema,”.”,table_name,
" into outfile ‘/bak/",table_schema,".",table_name,".csv’ fields terminated by ‘,’ ;")
FROM information_schema.tables WHERE table_schema =‘book’;
查看錶的字段
select COLUMN_NAME from information_schema.COLUMNS where table_name=‘books’ and table_schema = ‘book’;
編輯CSV文件並在第一行添加以上字段信息,用,
隔開
導入CSV文件到MongoDB
mongoimport -uroot -proot123 --port 27017 --authenticationDatabase admin -d book -c yourtablename --headerline --type=csv [-f ID,Name,Population] //添加了字段信息不用加該選項 --file /bak/yourtablename.csv
MySQL導出CSV
select * from book
into outfile '/tmp/test.csv
fields terminated by ‘,’
optionally enclosed by ‘"’
escaped by ‘"’
lines terminated by ‘\r\n’;
參數說明:
fields terminated by ‘,’ ------字段間以,號分隔
optionally enclosed by ‘"’ ------字段用"號括起
escaped by ‘"’ ------字段中使用的轉義符爲"
lines terminated by ‘\r\n’; ------行以\r\n結束
mysql導入csv:
load data infile ‘/tmp/test.csv’
into table test_info
fields terminated by ‘,’
optionally enclosed by ‘"’
escaped by ‘"’
lines terminated by ‘\r\n’;