【问题标题】:Changing schemas in mongoDB/mongoose更改 mongoDB/mongoose 中的模式
【发布时间】:2011-11-25 01:15:08
【问题描述】:

我开始使用 mongoDB 和 mongoose。我想知道人们如何管理不断发展的模式。例如,如果我从这样的架构开始:

user_ID : 123,
user_firstName : 'bob',
user_lastName : 'smith'

然后进化成这样:

user_ID: 123,
user_name: [first:'bob', last:'smith']

如何更新或管理使用旧架构设计建立的旧记录?

【问题讨论】:

    标签: mongodb schema database nosql


    【解决方案1】:

    迁移涉及简单数据转换的文档架构的一种方法是使用$exists 查找缺少新字段的文档并迁移它们。

    例如,将 firstName 和 lastName 转换为新的 user_name 字段:

    db.mycollection.find( { user_name : { $exists : false } } ).forEach(
        function (doc) {
            doc.user_name = {'first': doc.user_firstName, 'last': doc.user_lastName};
    
            // Remove old properties
            delete doc.user_firstName;
            delete doc.user_lastName;
    
            // Save the updated document
            db.mycollection.save(doc);
        }
    )
    

    对于更复杂的迁移,一些可能有用的工具是:

    【讨论】:

    • 以这种方式删除属性对我不起作用。我需要使用这样的东西db.mycollection.update({}, { $unset: { user_firstname: 1, user_lastname: 1 } }, { multi: true })
    猜你喜欢
    • 2011-11-28
    • 2015-06-27
    • 2011-12-11
    • 2018-10-18
    • 2013-04-07
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多