How to export Mysql tables to Mongodb : Mysql to MongoDB Migration
In this article you will learn how to export Mysql table data in mongo db using node js. Just follow these steps:
Step 1 : Set up your Node project
Open that folder in Vs code where you want to Initialize the new project.
Before that check for node installed or not . After that hit the below command.
npm init -y
This command will generate a package.json file.
Step 2: Install the required dependency for the project.
We will install Mysql and Mongoose Package for this project. Hit the below command to install the Packages.
npm install mysql mongoose
This command will install the Mysql package and the mongoose package. you can see the package install in the package.json file which holds all the dependencies required for the project.
Step 3: Now create a js file with the name 'export.js' or you can set up any name.
After that paste the below code in that file.
const mysql = require('mysql');
const mongoose = require('mongoose'); //required all the packages
//connecting mysql
const mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'your_mysql_username',
password: 'your_mysql_password',
database: 'your_mysql_database'
});
// connecting MongoDB
mongoose.connect('mongodb://localhost:27017/your_mongo_database');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// if you want to define a schema you can define it here or just put it as it is.
const dataSchema = new mongoose.Schema({}, { strict: false });
const Data = mongoose.model('Data', dataSchema);
// Fetch data from MySQL and insert into MongoDB
mysqlConnection.connect((err) => {
if (err) {
console.error('MySQL connection error:', err);
return;
}
console.log('Connected to MySQL');
mysqlConnection.query('SELECT * FROM your_mysql_table', async (err, results) => {
if (err) {
console.error('MySQL query error:', err);
return;
}
console.log('Data fetched from MySQL');
try {
await Data.insertMany(results);
console.log('Data inserted into MongoDB');
} catch (mongoErr) {
console.error('MongoDB insert error:', mongoErr);
} finally {
mysqlConnection.end();
mongoose.connection.close();
//end all the db connection
}
});
});
Explanation:
- Replace db username,password and database with yours. also in mongodb database name.
- {strict: false } is used in the schema to allow the field created in the collection based on mysql table data.
- replace mysql table with your table which you want to export in mongo db
- Used the insertMany() method to insert all the fetched data from mysql database table.
Step 4: Running the Script in node js
Hit the below command to run the script. The script will get all the rows from the mysql table and insert them all in mongodb database.
node export.js
If you have any questions feel free to ask.