dorestore
unknown
python
6 months ago
1.8 kB
2
Indexable
Never
import json import pymongo import mysql.connector # MongoDB connection settings mongodb_host = 'localhost' mongodb_port = 27017 mongodb_database = 'your_db_name' mongodb_collection = 'your_collection_name' # MySQL connection settings mysql_host = 'localhost' mysql_user = 'your_mysql_username' mysql_password = 'your_mysql_password' mysql_database = 'your_mysql_database' # Connect to MongoDB mongodb_client = pymongo.MongoClient(mongodb_host, mongodb_port) mongodb_db = mongodb_client[mongodb_database] mongodb_collection = mongodb_db[mongodb_collection] # Connect to MySQL mysql_connection = mysql.connector.connect( host=mysql_host, user=mysql_user, password=mysql_password, database=mysql_database ) mysql_cursor = mysql_connection.cursor() # Fetch data from MongoDB collection mongodb_data = mongodb_collection.find() # Transform and insert data into MySQL for document in mongodb_data: # Transform the document to MySQL-compatible format transformed_data = { 'id': document['_id'], # Assuming MongoDB _id field maps to 'id' in MySQL 'name': document['name'], # Assuming 'name' field exists in MongoDB 'age': document['age'], # Assuming 'age' field exists in MongoDB # Add more fields as needed and transform the data accordingly } # Insert the transformed data into MySQL mysql_insert_query = "INSERT INTO your_mysql_table (id, name, age) VALUES (%s, %s, %s)" mysql_insert_values = (transformed_data['id'], transformed_data['name'], transformed_data['age']) mysql_cursor.execute(mysql_insert_query, mysql_insert_values) # Commit the changes to MySQL mysql_connection.commit() # Close the connections mongodb_client.close() mysql_cursor.close() mysql_connection.close()