博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python迁移MySQL数据到MongoDB脚本
阅读量:6983 次
发布时间:2019-06-27

本文共 1957 字,大约阅读时间需要 6 分钟。

  MongoDB是一个文档数据库,在存储小文件方面存在天然优势。随着业务求的变化,需要将线上MySQL数据库中的行记录,导入到MongoDB中文档记录。

 

一、场景:线上MySQL数据库某表迁移到MongoDB,字段无变化。

 

二、Python模块

使用Python的torndb,pymongo和time模块。

*注释:首先安装setup.py,pip,MySQLdb

执行如下命令即可:

pip install torndb

pip install pymongo

 

三、脚本内容如下

[root ~]#cat nmytomongo.py

#!/usr/bin/env python #fielName: mytomongo.py #Author:xkops #coding: utf-8 import torndb,pymongo,time # connect to mysql database mysql = torndb.Connection(host='127.0.0.1', database='database', user='username', password='password') #connect to mongodb and obtain total lines in mysql mongo = pymongo.MongoClient('mongodb://ip').database mongo.authenticate('username',password='password') countlines = mysql.query('SELECT max(table_field) FROM table_name') count = countlines[0]['max(table_field)'] #count = 300 print count i = 0 j = 100 start_time = time.time() #select from mysql to insert mongodb by 100 lines. for i in range(0,count,100):     #print a,b     #print i     #print 'SELECT * FROM quiz_submission where quiz_submission_id > %d and  quiz_submission_id <= %d' %(i,j)     submission = mysql.query('SELECT * FROM table_name where table_field > %d and  table_field <= %d' %(i,j))     #print submission     if submission:         #collection_name like mysql table_name         mongo.collection_name.insert_many(submission)     else:         i +=100         j +=100         continue     i +=100     j +=100 end_time = time.time() deltatime = end_time - start_time totalhour = int(deltatime / 3600) totalminute = int((deltatime - totalhour * 3600) / 60) totalsecond = int(deltatime - totalhour * 3600 - totalminute * 60) #print migrate data total time consuming. print "Data Migrate Finished,Total Time Consuming: %d Hour %d Minute %d Seconds" %(totalhour,totalminute,totalsecond)

*注释:按照自己的需求更改上述代码中的数据库地址,用户,密码,库名,表名以及字段名等。

 

四、执行迁移脚本:

[root ~]#python nmytomongo.py &> /tmp/migratelog.txt &

脚本执行完成后查看/tmp/migratelog.txt数据迁移消耗的时间。

转载于:https://www.cnblogs.com/xkops/p/5442117.html

你可能感兴趣的文章
自定义ListBox,实现单多选切换(复选框)
查看>>
软件测试2019:第八次作业
查看>>
Centos下安装FTP并进行虚拟用户访问方式配置
查看>>
python day09
查看>>
拆系数FFT及其部分优化
查看>>
cocos2dx3.8 ios打包脚本编写
查看>>
wordpress搭建博客上传begin主题The themes is locked to another domain
查看>>
2019-04-16 SpringMVC 学习笔记
查看>>
C10K问题
查看>>
慕课网3-13编程练习:采用flex弹性布局制作页面主导航
查看>>
线程中死锁的demo
查看>>
canvas-7globleCompositeOperation.html
查看>>
Java并发(具体实例)——几个例子
查看>>
【待补】java开发Web Service
查看>>
两个有用的数组扩展方法
查看>>
英语发音规则---H字母
查看>>
js进阶 10-11/12 表单伪类选择器的作用
查看>>
C#中Invoke的用法
查看>>
pxe无人值守安装操作系统
查看>>
UESTC 2014 Summer Training #11 Div.2
查看>>