Search code examples
rubymongodbmigrationmongoid

Mongoid: convert embedded document into referenced/own collection


I need to convert an embedded document onto its own collection, so it can be referenced from another collection.

Lets suppose I have a Parent that embeds many Childs. I was thinking of something along this:

Parent.all.each do |p|
 p.childs.all.each do |c|
  c.raw_attributes['parent_id'] = p.id
 end
 p.save! #will save parent and cascade persist all childs onto their own coll
end

Is this an option? Ideally I would run this in a console and I would only change mongoid mappings from embed_* to has_*, so I wouldn't need to change the rest of my code or use another collection as staging.


Solution

  • I think, the code should look more like this (didn't test)

    child_coll = Mongoid.database.collection('children')
    
    Parent.all.each do |p|
      p.childs.all.each do |c|
        c.attributes['parent_id'] = p.id
    
        child_coll.insert c.attributes # save children to separate collection
      end
    
      p.childs = nil # remove embedded data
      p.save
    end
    

    After that, you can change your embeds_many to has_many and (hopefully) it should work well.