Pivotal Labs

Main menu

Skip to primary content
Skip to secondary content
  • About
  • Case Studies
  • Team
    • Executives
    • Locations
      • San Francisco (HQ)
      • Boston
      • Boulder
      • Denver
      • London
      • Los Angeles
      • New York
  • Community
    • Blogs
    • Tech Talks
    • Events
  • Careers
    • Lifestyle
    • Principles & Practices
    • Benefits
    • FAQ
    • Apply
  • Contact
    • Press Room
    • Press Releases
    • In The News
    • Press Kit
  • All
  • Labs
  • Standup
  • Tracker
Pivotal Labs

Mongoid Migrations using the Mongo Driver

Pivotal Labs
Saturday, January 29, 2011

In my last post, I modified a Mongoid::Document during a migration in order to access fields that where no longer defined in the class. This time I am using the mongo ruby driver directly to migrate data.

Since I am using Mongoid in this project, I will be using it to access the dependent mongo driver. This will prevent me from having to provide mongo with a connection string in my migration. I am also using mongoid_rails_migrations to roll out the change.

Initial Design

class User
  include Mongoid::Document
  field :first_name
  field :last_name
end

New Design

class User
  include Mongoid::Document
  field :name
end

Migration

class MergeUsersFirstAndLastName < Mongoid::Migration
  def self.up
    #get the mongo database instance from the Mongoid::Document
    mongo_db = User.db

    #query the collection for the fields needed for the migration
    user_hashes = mongo_db.collection("users").find({}, :fields => ["first_name", "last_name"])

    user_hashes.each do |user_hash|
      new_name = "#{user_hash['first_name']} #{user_hash['last_name']}"

      #update the new field
      mongo_db.collection("users").update({"_id" => user_hash["_id"]}, {"$set" => {"name" => new_name}})

      #remove old fields from collection
      mongo_db.collection("users").update({"_id" => user_hash["_id"]}, {"$unset" => { "last_name" => 1, "first_name" => 1}})
    end
  end
end

Resources

MongoDB Ruby Driver Tutorial

Querying with MongoDB Ruby Driver

Updating with MongoDB Ruby Driver

  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Pivotal Labs

Embedding Mongoid documents and data migrations

Pivotal Labs
Thursday, January 6, 2011

When first starting out with mongodb, it’s easy to make the wrong decision on whether to embed a document or not. Even if you made the correct decision at that moment, changing requirements may force you into a migration. So how do you migrate existing data when transitioning from a standalone document to an embedded document? This is what I came up with.

Initial Data Structure

class User
  include Mongoid::Document
  field :name
  references_many :sales
end

class Sale
  include Mongoid::Document
  field :price, :type => Integer
  referenced_in :user
end

Now with Sale embedded in User

class User
  include Mongoid::Document
  field :name
  embeds_many :sales
end

class Sale
  include Mongoid::Document
  field :price, :type => Integer
  embedded_in :user, :inverse_of => :sales
end

Migrating Sales Data

class EmbedSalesInUsers < Mongoid::Migration
  def self.up

    # pull your existing data into memory
    # consider batching for large data sets
    # Note that you must call query methods on the object you are migrating
    # for this method to work (i.e. you can not pull via User#sales)

    sales_attributes = while_stand_alone_doc(Sale) do
      Sale.all.map(&:attributes)
    end

    # now when you save your data, your fields will be embedded

    sales_attributes.each do |attributes|
      user = User.find(attributes[:user_id])
      user.sales << Sale.new(:price => attributes[:price])
    end

    # remove all the documents from the original collection

    while_stand_alone_doc(Sale) do
      Sale.destroy_all
    end
  end

  def self.while_stand_alone_doc(klass)
    # by changing the Mongoid::Document.embedded you can temporarily
    # modify which collection Mongoid looks to for your model's data store

    begin
      klass.embedded = false

      yield
    ensure
      klass.embedded = true
    end
  end

end

There are a couple things to note here.

  • The embedded flag in Mongoid::Document is not documented so it could easily change. This was working as of 2.0.0.beta.20
  • When you create the new embedded document, make sure you pass only the attributes you care about. Passing all attributes will add things that you no longer need like user_id in this case. (For clarity, attributes you assign will be persisted, though you will only have setters and getters for the fields you explicitly define in your document.
  • I am using mongoid_rails_migrations in this example
  • 0 Shares
  • Share on Facebook
  • Share on Twitter
Glenn Jahnke

Android Mongo Meetup

Glenn Jahnke
Tuesday, August 31, 2010

There is meeting tonight at 7pm in San Francisco about using MongoDB for mobile backend servers. Will Shulman from MongoLab will be giving the talk. They will also be offering food and prizes to attendees.

More details can be found at:

http://www.sfandroid.org/calendar/14367370/?eventId=14367370&action=detail

  • 0 Shares
  • Share on Facebook
  • Share on Twitter

Topics

  • agile (780)
  • rails (113)
  • testing (88)
  • ruby (83)
  • ruby on rails (70)
  • jobs (62)
  • javascript (55)
  • techtalk (44)
  • rspec (38)
  • ironblogger (32)
  • productivity (30)
  • activerecord (29)
  • gogaruco (29)
  • git (28)
  • nyc (27)
  • rubymine (26)
  • bloggerdome (23)
  • mobile (22)
  • process (21)
  • pivotal tracker (20)
  • cucumber (20)
  • jasmine (19)
  • design (18)
  • ios (18)
  • webos (17)
  • objective-c (17)
  • android (16)
  • palm (16)
  • "soft" ware (16)
  • fun (15)
  • tracker ecosystem (15)
  • ci (15)
  • cedar (15)
  • rails3 (14)
  • performance (14)
  • bdd (14)
  • gem (13)
  • css (13)
  • tdd (13)
  • selenium (12)
  • goruco (12)
  • bundler (12)
  • meetup (11)
  • railsconf (11)
  • nyc-standup (11)
  • capybara (10)
  • mac (10)
  • mojo (10)
  • chef (10)
  • api (10)
Subscribe to mongodb Feed
  • About
  • Case Studies
  • Team
  • Community
  • Careers
  • Contact
  • Labs
  • Events

Contact Us

contact@pivotallabs.com
+1 415-77-PIVOT
TwitterLinkedInFacebook

Pivotal Tracker

Tracker is the award-winning agile project management tool that enables real-time collaboration around a shared, prioritized backlog.
Visit pivotaltracker.com >