How can I run a migration to change the type of a field in Mongoid/MongoDB without losing any data?
In my case I'm trying to convert from a BigDecimal (stored as string) to an Integer to store some money. I need to convert the string decimal representation to cents for the integer. I don't want to lose the existing data.
I'm assuming the steps might be something like:
- create new Integer field with a new name, say
amount2
- deploy to production and run a migration (or rake task) that converts each
amount
to the right value foramount2
- (this whole time existing code is still using
amount
and there is no downtime from the users perspective) - take the site down for maintenance, run the migration one more time to capture any
amount
fields that could have changed in the last few minutes - delete
amount
and renameamount2
toamount
- deploy new code which expects
amount
to be an integer - bring site back up
It looks like Mongoid offers a rename
method: http://mongoid.org/docs/persistence/atomic.html#rename
But I'm a little confused how this is used. If you have a field named amount2
(and you've already deleted amount
), do you just run Transaction.rename :amount2, :amount
? Then I imagine this immediately breaks the underlying representation so you have to restart your app server after that? What happens if you run that while amount
still exists? Does it get overwritten, fail, or try to convert on it's own?
Thanks!