mysql的日志迁移到mango_mysql 向mongo迁移备忘

该博客介绍了如何将MySQL中的用户数据分表结构转换为MongoDB中的单一文档存储。通过遍历MySQL中的用户相关表格并使用UNION ALL查询合并数据,然后插入到MongoDB的用户文档中,实现数据迁移。在MongoDB中使用$addToSet确保数组字段不包含重复值,提高了查询效率。此过程适用于CLI或cron任务执行,避免浏览器超时。
摘要由CSDN通过智能技术生成

由于之前涉及mysql分表,把用户所关联的各种数据,我们暂设定为abcd,代表四种业务

比如userid 为1 ,可能属于 a1表,a2表,b3表,d4表。

现在要统一改为mongo

实现在user表中有一个abcd字段,类型是数组,分别存储相当应的表明

比如 abcd [0=>a1,1=>b2,2=>c3]这样。

思路也很简单,分表找到数据库属于abcd的所有表,联合查询,取到表名和pid(person id),然后插入更新到mongo abcd字段即可。

以下是简单实现:

$conn = mysql_connect("14.11.1.1", "d", "d2015");

mysql_select_db("dmp", $conn);//选择MYSQL数据库

mysql_query("set names utf8");//

$result = mysql_query("SHOW TABLES");

while ($row = mysql_fetch_array($result)) {

if (strstr($row[0], 'd_user_aaa_')) {

//$sql['aaa'][] = $row[0];

$aaa_sql .= "select '$row[0]' tbname,$row[0].pid from $row[0] union all ";

} elseif (strstr($row[0], 'd_user_ccc_')) {

$ccc_sql .= "select '$row[0]' tbname,$row[0].pid from $row[0] union all ";

} else if (strstr($row[0], 'd_user_ddd_')) {

$ddd_sql .= "select '$row[0]' tbname,$row[0].pid from $row[0] union all ";

} else if (strstr($row[0], 'd_user_ttt_')) {

$ttt_sql .= "select '$row[0]' tbname,$row[0].pid from $row[0] union all ";

}

}

$aaa_sql = rtrim($aaa_sql, "union all");

$ccc_sql = rtrim($ccc_sql, "union all");

$ddd_sql = rtrim($ddd_sql, "union all");

$ttt_sql = rtrim($ttt_sql, "union all");

// 可以统计下数据量大小

//echo "select count(*) from "."($ccc_sql)"." as nums";

// 测试 先来100条,一般这种情况在cli执行或者放在cron中执行,数据量大不适合在浏览器中跑,会超时。

//$aaa_sql .= " limit 100";

$ccc_sql .= " limit 100";

$res = mysql_query($ccc_sql);

$conn=new Mongo("mongodb://192.168.1.40:10001/test");

$collection=$conn->test->d_user;

while ($row = mysql_fetch_assoc($res)) {

$collection->update(array("pid"=>(int)$row['pid']),array('$addToSet'=>array('acdt'=>$row['tbname'])));

}

ps:myslq Union要进行重复值扫描,所以效率比较低。如果合并没有刻意要删除重复行,那么就使用Union All两个要联合的SQL语句 字段个数必须一样,而且字段类型要(一致)因为这些表里就是存了一个pid和时间,mongo的addtoset去重我猜又比mysql快,所以用了union all;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值