2011-09-26 57 views
8

我正在开始使用mongoDB和mongoose。我想知道人们如何管理演变模式。例如,如果我开始用这样的模式:更改mongoDB/mongoose中的模式

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

它发展到这样的事情:

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

我怎么可以更新或管理使用旧的架构设计建立的旧纪录?

回答

11

移植涉及简单数据转换的文档模式的一种方法是使用$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); 
    } 
) 

对于更复杂的迁移一些工具可帮助有: