2011-09-26 60 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); 
    } 
) 

對於更復雜的遷移一些工具可幫助有: