如何把mysql中数据迁移到mongodb

时间:2024-10-23 05:07:58

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')

© 手抄报圈