MONGOID Cheat Sheet

MONGOID is an Object-Relational Mapper that enables Ruby on Rails to use the NoSQL Database MongoDB as a backend. My newest project is wholly based on MongoDB.

Here’s my little cheat sheet that acts as a quick reference during my programming sprints.

The MONGOID Cheat Sheet

Example

class User
  include Mongoid::Document
  include Mongoid::Timestamps # adds automagic fields created_at, updated_at
  references_many :posts
  embeds_one :profile, :dependent => :destroy
  field :fieldname, :type => Array / BigDecimal / Boolean / Date / DateTime
                           / Float / Hash / Integer / String / Symbol / Time
  index :fieldname
end

Relations

Embedding data in the same table:

embeds_one :profile
embeds_many :settings
embedded_in :user, :inverse_of => :settings

Referencing data in an other table:

referenced_in :user
references_one :profile, :inverse_of => user
references_many :photos, :inverse_of => user

Persistence

In order to make sure data is actually to be written to disk, you need to tell mongoid

.safely.save
(!Mongoid only fires the callback of the document that the persistence action was executed on)

Queries

.where(:amount.gt => 100, :active => true)
.any_in(:category => array)
.all_in(:category => array)
.any_of({ :shape => "round" }, { :color => "red" })
.and(:amount.gt => 100, :account_status => "active")
.excludes(:status => "blocked")
.not_in(:status => ["blocked", "unverified"])
.only(:first_name, :last_name) # only retrieve these fields
.limit(20)
.skip(100)

Order

.desc(:last_name).asc(:first_name)
.order_by(:last_name.desc, :first_name.asc, :city.desc)

Criterias

.where(:title.all => ["Sir"])
.where(:age.exists => true)
.where(:age.gt => 18)
.where(:age.gte => 18)
.where(:title.in => ["Sir", "Madam"])
.where(:age.lt => 55)
.where(:age.lte => 55)
.where(:title.ne => "Mr")
.where(:title.nin => ["Esquire"])
.where(:aliases.size => 2)
.where(:location.near => [ 22.5, -21.33 ])
.where(:location.within => { "$center" => [ [ 50, -40 ], 1 ] })

Calculations

.max(:age)
.min(:quantity)
.sum(:total)

Rake Tasks

db:create
db:create_indexes
db:drop
db:migrate
db:schema:load
db:seed
db:setup
db:test:prepare

Make sure to also check out the MONGOID docs and The Definitive Guide to MongoDB.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>