use*_*767 53 mysql database mongodb
有没有简单的方法将数据库从mysql更改为mongoDB?
或者更好的任何人建议我做好教程
Gat*_* VP 49
有没有简单的方法将数据库从mysql更改为mongoDB?
方法#1:以CSV格式从MySQL导出,然后使用mongoimport工具.但是,在处理二进制数据的日期方面,这并不总是有效.
方法#2:用您选择的语言编写转移脚本.基本上你编写一个程序,一次从MySQL读取一个元素,然后将其插入到MongoDB中.
方法#2优于#1,但仍然不够.
MongoDB使用集合而不是表.MongoDB不支持连接.在我看过的每个数据库中,这意味着MongoDB中的数据结构与MySQL中的结构不同.
因此,没有用于将SQL移植到MongoDB的"通用工具".您的数据需要在到达MongoDB之前进行转换.
And*_*w K 22
如果你正在使用Ruby,你也可以尝试:Mongify
这是一种将数据从RDBS转换为MongoDB而不会丢失任何内容的超级简单方法.
Mongify将读取您的mysql数据库,为您构建一个翻译文件,您所要做的就是映射您希望数据转换的方式.
它支持:
有关详细信息,请访问:http://mongify.com/getting_started.html
主页上还有一个短短5分钟的视频,向您展示它是多么容易.
为此,我使用 Node.js 执行了以下操作:
var mysql = require('mysql');
var MongoClient = require('mongodb').MongoClient;
function getMysqlTables(mysqlConnection, callback) {
mysqlConnection.query("show full tables where Table_Type = 'BASE TABLE';", function(error, results, fields) {
if (error) {
callback(error);
} else {
var tables = [];
results.forEach(function (row) {
for (var key in row) {
if (row.hasOwnProperty(key)) {
if(key.startsWith('Tables_in')) {
tables.push(row[key]);
}
}
}
});
callback(null, tables);
}
});
}
function tableToCollection(mysqlConnection, tableName, mongoCollection, callback) {
var sql = 'SELECT * FROM ' + tableName + ';';
mysqlConnection.query(sql, function (error, results, fields) {
if (error) {
callback(error);
} else {
if (results.length > 0) {
mongoCollection.insertMany(results, {}, function (error) {
if (error) {
callback(error);
} else {
callback(null);
}
});
} else {
callback(null);
}
}
});
}
MongoClient.connect("mongodb://localhost:27017/importedDb", function (error, db) {
if (error) throw error;
var MysqlCon = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
port: 8889,
database: 'dbToExport'
});
MysqlCon.connect();
var jobs = 0;
getMysqlTables(MysqlCon, function(error, tables) {
tables.forEach(function(table) {
var collection = db.collection(table);
++jobs;
tableToCollection(MysqlCon, table, collection, function(error) {
if (error) throw error;
--jobs;
});
})
});
// Waiting for all jobs to complete before closing databases connections.
var interval = setInterval(function() {
if(jobs<=0) {
clearInterval(interval);
console.log('done!');
db.close();
MysqlCon.end();
}
}, 300);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77018 次 |
| 最近记录: |