Skip to content

Instantly share code, notes, and snippets.

@icebreaker
Created February 15, 2011 09:11
Show Gist options
  • Save icebreaker/827298 to your computer and use it in GitHub Desktop.
Save icebreaker/827298 to your computer and use it in GitHub Desktop.
Mongoid cheat sheet

The MONGOID Cheat Sheet

( Source: the mongoid cheatsheet )

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment