【问题标题】:How to merge two tables into one using mongify如何使用 mongify 将两个表合并为一个
【发布时间】:2015-03-01 12:04:00
【问题描述】:

我计划将我的应用程序数据库从 Mysql 迁移到 Mongo,并且架构更改很少。在我的新模式中,我将两个 Mysql 表合并到一个 Mongo 集合中。我想使用 mongify (https://github.com/anlek/mongify) gem 将我现有的 Mysql 数据填充到具有更新模式的 Mongo 中。

如何做到这一点? mongify有没有办法将两个Mysql表合并为一个?

Mysql 表

user
    id
    name
    nickname
    type

user_role
    id
    role
    alias
    user_id

我在 Mongo 中将以上两个表合并为一个集合

user
    id
    name
    type
    role
    alias

【问题讨论】:

    标签: mysql mongodb migration schema database-migration


    【解决方案1】:

    尝试左连接:(表将被合并)

    SELECT column_name(s)
    FROM table1
    LEFT JOIN table2
    ON table1.column_name=table2.column_name;
    

    将该数据导出为sql格式并上传到mongodb

    SELECT country INTO customerCountry
     FROM customers
     WHERE customerNumber = p_customerNumber;
    
        CASE customerCountry -- Here you have to see if that alias data is set
     WHEN  'USA' THEN
        SET p_shiping = '2-day Shipping'; -- here you have to write Update Query
     ELSE
        SET p_shiping = '5-day Shipping';
     END CASE;
    

    我觉得可能对你有帮助

    【讨论】:

    • 感谢您的宝贵回复!!!用户表有“昵称”,第二个表有“别名”字段。如果我需要将字段“昵称”重命名为“别名”,并且需要将 user_info.alias 值放入用户表中。我该怎么做呢?请提供您的意见...
    • 是否要从 user_role.alias 列中替换 user.nickname 中的所有数据
    • 在这种情况下,我建议您在 CASE 中使用子查询,例如如果别名中有数据,则使用该别名更新您的订单昵称。
    【解决方案2】:

    使用 MySQL 中的 JOIN 获取数据并将该数据加载到 MongoDB:

    试试这个:

    SELECT U.id, U.name, U.type, UR.role
    FROM USER U 
    INNER JOIN user_role UR ON U.id = UR.user_id;
    

    【讨论】:

      【解决方案3】:

      如果很难临时合并两个表,则另一种方法是运行mongo shell script post-hoc;它们非常易于编程(几行 js)并且易于执行。加一个可以应用任何需要的转换,例如转换为 mongo 中允许但 mysql 中不允许的 json/bson 数组。

      假设 mongo 中有一个 user 和 user_role 集合(或表)。

      db.user_role.find({}).forEach(function(doc) {  
         var roles = doc.roles;
         // convert mysql format here if needed.
         //var roles_array = JSON.parse(roles) // or whatever?
      
         //var alias = doc.alias;
         // if alias is null empty or ??
      
         // dont upsert to avoid orphaned user_role records
         db.user.update({"_id": doc.user_id}, {"roles": roles, "alias", doc.alias }, {upsert: false, multi: false});
      
      }
      

      然后使用 mongo shell 执行

      mongo localhost:27017/test myjsfile.js

      【讨论】:

        猜你喜欢
        • 2021-07-30
        • 1970-01-01
        • 1970-01-01
        • 2011-11-24
        • 2014-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多