Question

It seems like Mongoid is now the superior ORM for Mongo based on performance and development activity. Unfortunately, we're on MongoMapper and need to migrate.

Are there any concerns or stumbling blocks we should be aware of? We have found a few outdated articles on Google and tried posting on the Mongoid Google Groups (though we were prohibited), but would love thoughts from SO members who have done this in the past.

We're on Rails 3.2.12.

Thanks!

Was it helpful?

Solution

Both of them are great MongoDB Libraries for Ruby. But if you want to switch, here are some notes:

Migrating MongoMapper ORM to Mongoid ORM - Notes

  • Configure the database connection.

  • Replace configuration yaml file(includes replica configuration).

  • Configure Mongoid specific options. e.g - raise_not_found_error: false. if you don't want an error every time a query returns nothing...

  • Change all models definations - include MongoMapper::Document to include Mongoid::Document

  • Change the format for all fields definitions.

  • In mongoid, you should specipy the timestamp: include Mongoid::Timestamps

  • Change validation. e.g: :in => ARRAY, will be: validates :name, presence: true, inclusion: { in: ARRAY }

  • Change indexes.

  • Change order_by format. e.g: MM: Model.all(:order => 'name'). Mongoid: Model.order_by('name ASC')

  • Error is a keyword in Mongoid. So if you have a model named Error, you should change it.

  • Pagination format is different, using another gem.

  • The primary key index entry in MM is id. In Mongoid it's _id, if you have other code relying on .id in the object JSON, you can override as_json function in your Model to create the JSON structure you want.

  • In MM, Model.fields(:id, :name) ,limits the fields returned from the database to those supplied to the method. In Mongoid it's Model.only(:name,:id)

  • Some queries changes:

    1. Selecting objects by array: MM: Model.where(:attr.in => [ ] ) and Model.where(:attr => [ ] ) . Mongoid is only: Model.where(:attr.in => [ ] )

    2. Map option of MM is equivalent to the Mid's pluck. Model.map(&:name) --to-- Model.pluck(:name)

    3. Mongoid doesn't support find query for nil. e.g: value = nil. Model.find(value) will throw an error : "Calling Document .find with nil is invalid". So in mongoid we should do: Model.find(value || "").

    4. In MM: Model.find_or_initialize_by_name("BOB"). In Mongoid Model.find_or_initialize_by(name: "BOB").

    5. MM can be used in those two options: Model.where({:name => 'BOB'}).first, and also Model.first({:name => 'BOB'}). Mongoid has only first option.

    6. In MM, to update multiple objects: Model.set({conditions},attr_to_update). In Mongoid: Model.where(conditions).update_all(attr_to_update).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top