/***************************************
* Usage: php ex.php tableName [pretty_collection]
* 如果pg有多个模式,应使用类似server.tableName的格式
* 如果传了pretty_collection,mongo中的集合名将变成 模式_表名
*
***************************************/
function list_all_tables($dbname)
{
$pdo = new PDO('pgsql:host=localhost;port=5432;dbname=test', 'postgres', 'root');
$result = $pdo->query('show tables');
while ($row = $result->fetch(PDO::FETCH_NUM)) {
var_dump($row[0]);
}
}
/**
* 插入数据到mongo
*
*/
function export_to_mongo($dataset, $collname)
{
$client = new MongoClient();
$db = $client->test;
$coll = $db->{$collname};
$coll->insert($dataset);
echo 'one record inserted...' . PHP_EOL;
}
if (count($argv) < 2) {
exit('参数不够');
}
$user = 'postgres';
$password = 'root';
$dbname = 'mlib';
$dns = "pgsql:host=localhost;port=5432;dbname=$dbname";
try {
$pdo = new PDO($dns, $user, $password);
$table = $argv[1];
if (isset($argv[2])) {
$table = implode('_', explode('.', $table));
}
$stmt = $pdo->query("select * from $table");
if ($stmt) {
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($arr as $data) {
export_to_mongo($data, $table);
}
} else {
echo 'invalid parameter: ' . $table . PHP_EOL;
exit;
}
} catch (Exception $e) {
print 'error: ' . $e->getMessage() . PHP_EOL;
die();
}
$pdo = null;
一键复制
编辑
Web IDE
原始数据
按行查看
历史