1.首先将mysql的数据库导出为json文件
2.导出后将文件存放到文件夹里
3.使用node命令将导出的json数据处理一下;
我的文件目录为'D:/Users/liuhuanjie/Desktop/1'; // 文件夹路径,修改为自己的
新建一个js文件作为脚本,比如import.js
脚本如下,然后运行node import.js
const fs = require('fs');
const path = require('path');
const folderPath = 'D:/Users/liuhuanjie/Desktop/1'; // 文件夹路径
// 读取文件夹下所有文件名
fs.readdir(folderPath, (err, files) => {
if (err) {
console.error('Error reading folder:', err);
return;
}
// 遍历文件名数组
files.forEach(file => {
const filePath = path.join(folderPath, file);
// 仅处理 JSON 文件
if (file.endsWith('.json')) {
console.log('Processing file:', filePath);
modifyJSON(filePath); // 调用修改 JSON 结构的函数
}
});
});
// 修改 JSON 结构的函数
function modifyJSON(filePath) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
try {
const jsonContent = JSON.parse(data);
if (jsonContent.RECORDS) {
const modifiedData = JSON.stringify(jsonContent.RECORDS, null, 2);
// 写入修改后的 RECORDS 到原文件
fs.writeFile(filePath, modifiedData, 'utf8', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File has been successfully modified:', filePath);
});
} else {
console.log('No RECORDS found in the file:', filePath);
}
} catch (err) {
console.error('Error parsing JSON:', err);
}
});
}
4.将处理完的json文件,导入mongodb数据库里,我使用的数据库名为forge //修改为自己的
const fs = require('fs');
const { MongoClient } = require('mongodb');
const path = require('path');
const folderPath = 'D:/Users/liuhuanjie/Desktop/1'; // 文件夹路径
const mongoURI = 'mongodb://localhost:27017'; // MongoDB数据库连接URI
const dbName = 'forge'; // 数据库名称
// 连接到MongoDB数据库
MongoClient.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }, async (err, client) => {
if (err) {
console.error('Error connecting to MongoDB:', err);
return;
}
console.log('Connected to MongoDB successfully.');
try {
const db = client.db(dbName);
// 读取文件夹下所有文件名
const files = await fs.promises.readdir(folderPath);
// 遍历文件名数组
for (const file of files) {
const filePath = path.join(folderPath, file);
// 仅处理 JSON 文件
if (file.endsWith('.json')) {
console.log('Processing file:', filePath);
const collectionName = path.basename(file, '.json'); // 获取集合名称
await importJSONToMongo(db, filePath, collectionName); // 导入数据到MongoDB
}
}
console.log('All files imported to MongoDB successfully.');
} catch (err) {
console.error('Error importing files to MongoDB:', err);
} finally {
// 关闭MongoDB连接
client.close();
}
});
// 导入JSON数据到MongoDB集合
async function importJSONToMongo(db, filePath, collectionName) {
const data = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(data);
const collection = db.collection(collectionName);
await collection.insertMany(jsonData);
console.log('Data imported to collection:', collectionName);
}
5.最后就成功了