MongoDB 和 MySQL 是两种不同类型的数据库系统。MongoDB 是一个基于分布式文件存储的开源数据库系统,使用的数据结构是类似 JSON 的 BSON 格式,因此可以存储比较复杂的数据类型。而 MySQL 是一个关系型数据库管理系统,使用 SQL 进行数据操作。
MongoDB 同步 MySQL 指的是将 MySQL 数据库中的数据同步到 MongoDB 数据库中,或者反过来,将 MongoDB 中的数据同步到 MySQL 中。这种同步通常用于数据迁移、备份、多数据库环境下的数据一致性等场景。
原因:
解决方案:
解决方案:
mongodb
、mysql
模块进行 MongoDB 同步 MySQL)const MongoClient = require('mongodb').MongoClient;
const mysql = require('mysql');
// MongoDB 连接配置
const mongoUrl = 'mongodb://localhost:27017';
const dbName = 'myMongoDB';
const collectionName = 'myCollection';
// MySQL 连接配置
const mysqlConfig = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'myMySQLDB'
};
// 连接 MongoDB
MongoClient.connect(mongoUrl, { useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
const db = client.db(dbName);
const collection = db.collection(collectionName);
// 连接 MySQL
const mysqlConnection = mysql.createConnection(mysqlConfig);
mysqlConnection.connect((err) => {
if (err) throw err;
// 查询 MongoDB 数据并同步到 MySQL
collection.find({}).toArray((err, docs) => {
if (err) throw err;
docs.forEach(doc => {
// 根据需要转换数据格式
const mysqlQuery = `INSERT INTO myTable SET ?`;
mysqlConnection.query(mysqlQuery, doc, (err, result) => {
if (err) throw err;
console.log(`Inserted ${result.affectedRows} row(s) into MySQL`);
});
});
// 关闭连接
mysqlConnection.end();
client.close();
});
});
});
领取专属 10元无门槛券
手把手带您无忧上云