假设我有一个现有的数据集,其中某些内容是嵌入式文档,但我们希望将其转换为参考。是否有任何一种自动或半自动的方式来进行这种重构。
问问题
236 次
1 回答
1
重构本身很简单。只需将“embeds_one”替换为“has_one”(或用适当的术语替换您的映射器库)。数据迁移会带来一些痛苦。或者也许不会。这是我在 10 分钟内完成的一个小红宝石脚本。它应该涵盖我认为您需要的内容。
source_collection = 'users'
field_to_expand = 'address'
parent_field = 'user_id'
expanded_collection = 'addresses'
require 'mongo'
db = Mongo::Connection.new.db('test')
users = db.collection(source_collection)
addresses = db.collection(expanded_collection)
# prepare test data
users.remove()
addresses.remove()
users.insert({name: 'Joe', address: {city: 'Rio de Janeiro'}})
users.find().to_a # => [{"_id"=>BSON::ObjectId('50614e910ed4c08a6a000001'), "name"=>"Joe", "address"=>{"city"=>"Rio de Janeiro"}}]
users.find().each do |u|
# move subdocument to a separate collection
addr = u[field_to_expand]
addr[parent_field] = u['_id']
addresses.insert(addr)
# erase from original document
users.update({_id: u['_id']}, {'$unset' => {field_to_expand => 1}})
end
users.find().to_a # => [{"_id"=>BSON::ObjectId('50614e910ed4c08a6a000001'), "name"=>"Joe"}]
addresses.find().to_a # => [{"_id"=>BSON::ObjectId('50614e910ed4c08a6a000002'), "city"=>"Rio de Janeiro", "user_id"=>BSON::ObjectId('50614e910ed4c08a6a000001')}]
于 2012-09-25T06:28:12.313 回答