1

何かが埋め込まれたドキュメントである既存のデータセットがありますが、代わりにそれを参照に変換したいとします。このリファクタリングを行うための自動または半自動の方法はありますか?

4

1 に答える 1

1

リファクタリング自体は簡単です。「embeds_one」を「has_one」に交換するだけです (または、マッパー ライブラリの適切な用語を置き換えます)。多少の痛みを引き起こすのはデータ移行です。あるいは、そうではないかもしれません。これは、私が 10 分もかからずに作成した小さな Ruby スクリプトです。それはあなたが必要だと私が思うものをカバーするべきです.

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 に答える