Reputation: 73
How do you handle schema changes in Mongo db e.g. say after refactoring you change your object schema design and that impacts the document schema. Is there a way to update the document schema?
Upvotes: 1
Views: 1376
Reputation: 33145
You can run an update on the entire schema, removing fields, or adding fields and setting them to calculated values, if that's what you're getting at.
Say you had an x field, and you want to add a y field that should be set to x/2, you could do something like this:
PRIMARY> db.test.insert({x:15});
PRIMARY> db.test.insert({x:30});
PRIMARY> db.test.insert({x:50});
PRIMARY> db.test.find();
{ "_id" : ObjectId("4f9df1ebed2b924eedb8cad9"), "x" : 15 }
{ "_id" : ObjectId("4f9df1eeed2b924eedb8cada"), "x" : 30 }
{ "_id" : ObjectId("4f9df1f1ed2b924eedb8cadb"), "x" : 50 }
PRIMARY> db.test.find().forEach(function(doc) {
doc.y = doc.x/2;
db.test.save(doc);
});
PRIMARY> db.test.find();
{ "_id" : ObjectId("4f9df1ebed2b924eedb8cad9"), "x" : 15, "y" : 7.5 }
{ "_id" : ObjectId("4f9df1eeed2b924eedb8cada"), "x" : 30, "y" : 15 }
{ "_id" : ObjectId("4f9df1f1ed2b924eedb8cadb"), "x" : 50, "y" : 25 }
Upvotes: 3