如何把mysql中数据迁移到mongodb

时间:2026-02-14 02:07:19

1、使用python中的mysql.connector库MySQL数据库:import mysql.connector,使用pymongo连接mongodb数据库:import pymongo。 

2、从MySQL中读取数据,包括数据的字段名称:

sql = 'select * from %s where id = %s'%(table_names[1],order_id)cursor.execute(sql)rows = cursor.fetchall()column_names = [d[0] for d in cursor.description]

3、使用继承子dict的类将读取到的数据转换成字典的数组,以便于存入mongodb中

#定义一个继承自dict的类class Row(dict):    """A dict that allows for object-like property access syntax."""    def __getattr__(self, name):        try:            return self[name]        except KeyError:            raise AttributeError(name)

4、将数据转换成json格式:

item = [Row(zip(column_names, row)) for row in rows]item = item[0]if item:    '''merge_set_by_set是我定义的把多个表相关联的数据表的数据存放到一起组合成一个json的函数'''    merge_set_by_set(mongo_item, item,table_names[0])

5、将数据存放到mongodb中

if mongo_items:    try:        mongo.order_info1.insert_many(mongo_items)        print('=success insert into mongodb')    except:        print('fail')

© 2026 一点资料
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com