SlideShare a Scribd company logo
MongoDB
{ name: “mongo”, type: “db” }
“MongoDB is designed to be
human-oriented.
It reduces the burden of
programming.
It tries to push jobs back to
machines. You can accomplish more
tasks with less work, in smaller yet
readable code.” - Banker
built for speed
document/collection oriented
dynamic queries and indexes
   replication and failover
websites from yesterday and today
       high volume traffic
          high scalability
  storage of objects and JSON
caveats
no transactions
relationships
MongoDB with Ruby
 because we all want ActiveRecord...
mongo-ruby-driver
 mongomapper
   mongoid
Spiff uses Mongoid

class Post
	   include Mongoid::Document
	   field :title, :type => String
	   field :body, :type => String
end




@posts = @db.collection('posts')
@document = {:title => "MongoDB on Rails",
             :body => "Revelatory! Loved it!"}
@posts.save(@document)
Associations in Mongoid

class Post
	   include Mongoid::Document
	   field :title, :type => String
	   field :body, :type => String
	   has_many :comments
end


class Comment
	   include Mongoid::Document
	   field :rant, :type => String
	   belongs_to :post, :inverse_of => :comments
end

                       This creates an Embedded Document.


@posts = @db.collection('posts')
@document = {:title => "MongoDB on Rails",
             :body => "Revelatory! Loved it!",
             :comments => [{:rant => “I completely disagree”}]
             }
@posts.save(@document)
Keys, Validations, Timestamps & Hooks
class Post
	   include Mongoid::Document
	   include Mongoid::Timestamps

	   field :title, :type => String
	   field :body, :type => String
	   field :slug, :type => String
	   has_many :comments
	

   has_key :title, :unique => true   # “Audi IMS” becomes “audiims”


	   validates_presence_of :title, :body
	   validates_unqiueness_of :title

	   before_save :set_slug

	   def set_slug

    self.slug = “#{title.parameterize}-#{body[0..3]}”
	   end
end
Versioning a Mongo Document
class Post
	   include Mongoid::Document
	   include Mongoid::Timestamps
	   include Mongoid::Versioning

	   field :title, :type => String
	   field :body, :type => String
	   field :slug, :type => String
	   has_many :comments
	

   has_key :title, :unique => true   # “Audi IMS” becomes “audiims”


	   validates_presence_of :title, :body
	   validates_unqiueness_of :title

	   before_save :set_slug

	   def set_slug

    self.slug = “#{title.parameterize}-#{body[0..3]}”
	   end
end
Access related items
class Post
	   include Mongoid::Document
	   include Mongoid::Timestamps
	   include Mongoid::Versioning

	    field :title, :type => String
	    field :body, :type => String
	    field :slug, :type => String
	    has_many :comments
	
	    belongs_to_related :account
	    has_many_related :sources	

	   .....
end




        database.yml meet database.mongo.yml
But does it blend?



Post.all(:conditions => { :title => “Rails 2.3” })
Post.find(:all, ...)
Post.first(...)

Post.find_or_create_by(:title => “Merb is dead”)
Post.find_or_initialize_by(...)

Associations:
 @post.comments.all
fuck SQL! Criteria is the shit.

Criteria#all - perform exact matches

    Post.criteria.all(:title => [ “Rails”, “2.3” ])

Criteria#find - match key/value
	    Post.criteria.and(:created_at.gt => 2.months.ago)

Criteria#exclude
	    Post.criteria.exclude(:created_at => Date.today)

Criteria#id - match document id

    Post.criteria.id(“4b2fe28ee2dc9b5f7b000029”)

Criteria#in - match any of the values in an array

    Post.criteria.in(:title => [“Merb”, “Rails”, “Ruby”]

Criteria#order_by
	    Post.criteria.order_by([[:created_at, :desc], [:title, :asc] ])

Criteria also has #limit, #not_in, #only, #skip
arithmetic, grouping & aggregation
  #max, #min, #sum, #aggregate, #group
“But what about named scopes dude?!” -Gabe




named_scope :active, criteria.where(:active => true) do
 def count
  size
 end
end

named_scope :inactive, :where => { :active => false }

named_scope :frags_over, lambda { |count| { :where => { :frags.gt => count } } }

named_scope :deaths_under, lambda { |count| criteria.where(:deaths.lt => count) }
You can chain any of the Criteria API
Post.in(:title => [“Rails”, “Ruby”]).where(:created_at.gt => 2.months.ago).skip(10)


  class Post
  	   include Mongoid::Document
  	
     class << self
        def ruby_related
         criteria.in(:title => [“Ruby”, “Rails”])
        end

          def in_last_two_months
           criteria.where(:created_at.gt => 2.months.ago))
          end
        end
  end

  Post.ruby_related.in_last_two_months
additional mongoid features
         Composite Keys
             Indexing
           Inheritance
  native MongoDB expressions
MongoDB & Mongoid with Rails

More Related Content

PDF
Mongoid in the real world
PDF
MongoDB and Ruby on Rails
PDF
ActiveRecord vs Mongoid
PDF
Using Mongoid with Ruby on Rails
KEY
Practical Ruby Projects With Mongo Db
PPTX
Building Your First Application with MongoDB
PDF
Build your first MongoDB App in Ruby @ StrangeLoop 2013
PDF
Building your first app with mongo db
Mongoid in the real world
MongoDB and Ruby on Rails
ActiveRecord vs Mongoid
Using Mongoid with Ruby on Rails
Practical Ruby Projects With Mongo Db
Building Your First Application with MongoDB
Build your first MongoDB App in Ruby @ StrangeLoop 2013
Building your first app with mongo db

What's hot (20)

PDF
Learn Learn how to build your mobile back-end with MongoDB
PDF
Building Apps with MongoDB
PPTX
Conceptos básicos. seminario web 3 : Diseño de esquema pensado para documentos
PPT
Advanced Json
PPTX
Webinar: Getting Started with MongoDB - Back to Basics
PDF
MongoDB, Hadoop and humongous data - MongoSV 2012
KEY
PPTX
Webinar: Back to Basics: Thinking in Documents
ODP
MongoDB : The Definitive Guide
KEY
Schema Design with MongoDB
PPTX
Intro To Mongo Db
PDF
10gen Presents Schema Design and Data Modeling
PPT
Mongo Web Apps: OSCON 2011
PDF
Getting started with MongoDB and Scala - Open Source Bridge 2012
PPTX
Back to Basics Webinar 2: Your First MongoDB Application
PPTX
Back to Basics Webinar 1 - Introduction to NoSQL
PPTX
Back to Basics Webinar 3 - Thinking in Documents
PPTX
Data Modeling for the Real World
PPTX
Webinar: Data Modeling Examples in the Real World
PPTX
Building Your First App: An Introduction to MongoDB
Learn Learn how to build your mobile back-end with MongoDB
Building Apps with MongoDB
Conceptos básicos. seminario web 3 : Diseño de esquema pensado para documentos
Advanced Json
Webinar: Getting Started with MongoDB - Back to Basics
MongoDB, Hadoop and humongous data - MongoSV 2012
Webinar: Back to Basics: Thinking in Documents
MongoDB : The Definitive Guide
Schema Design with MongoDB
Intro To Mongo Db
10gen Presents Schema Design and Data Modeling
Mongo Web Apps: OSCON 2011
Getting started with MongoDB and Scala - Open Source Bridge 2012
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 1 - Introduction to NoSQL
Back to Basics Webinar 3 - Thinking in Documents
Data Modeling for the Real World
Webinar: Data Modeling Examples in the Real World
Building Your First App: An Introduction to MongoDB
Ad

Similar to MongoDB & Mongoid with Rails (20)

KEY
MongoDB at RubyEnRails 2009
PDF
Mongodb mongoid
PDF
MongoDB at FrozenRails
PPTX
Simple MongoDB design for Rails apps
KEY
The Ruby/mongoDB ecosystem
PDF
Timothy N. Tsvetkov, Rails 3.1
PDF
Pyconie 2012
PDF
Rails Loves MongoDB
PDF
Tame Accidental Complexity with Ruby and MongoMapper
PPTX
Grzegorz Witek - MongoDB + RoR, Mongoid (PRUG 1.0)
KEY
Introduction to MongoDB
KEY
Benefits of using MongoDB: Reduce Complexity & Adapt to Changes
PDF
Mongo db eveningschemadesign
KEY
Schema Design by Example ~ MongoSF 2012
PDF
The emerging world of mongo db csp
KEY
MongoDB at ZPUGDC
KEY
MongoDB NYC Python
PDF
Mongo db
KEY
MongoDB
ZIP
Barcamp Auckland Rails3 presentation
MongoDB at RubyEnRails 2009
Mongodb mongoid
MongoDB at FrozenRails
Simple MongoDB design for Rails apps
The Ruby/mongoDB ecosystem
Timothy N. Tsvetkov, Rails 3.1
Pyconie 2012
Rails Loves MongoDB
Tame Accidental Complexity with Ruby and MongoMapper
Grzegorz Witek - MongoDB + RoR, Mongoid (PRUG 1.0)
Introduction to MongoDB
Benefits of using MongoDB: Reduce Complexity & Adapt to Changes
Mongo db eveningschemadesign
Schema Design by Example ~ MongoSF 2012
The emerging world of mongo db csp
MongoDB at ZPUGDC
MongoDB NYC Python
Mongo db
MongoDB
Barcamp Auckland Rails3 presentation
Ad

More from Justin Smestad (7)

PDF
Introduction to MongoDB
KEY
MongoDB in the Cloud -- Mongo Boulder
KEY
MongoMachine Presentation for MongoSV 2010
KEY
Mongo Seattle - The Business of MongoDB
KEY
Testing Web Services in Ruby
KEY
Boulder StaleFish Presentation
KEY
Refactor Me presentation
Introduction to MongoDB
MongoDB in the Cloud -- Mongo Boulder
MongoMachine Presentation for MongoSV 2010
Mongo Seattle - The Business of MongoDB
Testing Web Services in Ruby
Boulder StaleFish Presentation
Refactor Me presentation

Recently uploaded (20)

PPT
Teaching material agriculture food technology
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Approach and Philosophy of On baking technology
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Cloud computing and distributed systems.
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
Teaching material agriculture food technology
Understanding_Digital_Forensics_Presentation.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Approach and Philosophy of On baking technology
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Machine learning based COVID-19 study performance prediction
Cloud computing and distributed systems.
Review of recent advances in non-invasive hemoglobin estimation
Mobile App Security Testing_ A Comprehensive Guide.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Building Integrated photovoltaic BIPV_UPV.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Unlocking AI with Model Context Protocol (MCP)
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
MIND Revenue Release Quarter 2 2025 Press Release
The AUB Centre for AI in Media Proposal.docx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Per capita expenditure prediction using model stacking based on satellite ima...

MongoDB & Mongoid with Rails

  • 1. MongoDB { name: “mongo”, type: “db” }
  • 2. “MongoDB is designed to be human-oriented. It reduces the burden of programming. It tries to push jobs back to machines. You can accomplish more tasks with less work, in smaller yet readable code.” - Banker
  • 3. built for speed document/collection oriented dynamic queries and indexes replication and failover
  • 4. websites from yesterday and today high volume traffic high scalability storage of objects and JSON
  • 8. MongoDB with Ruby because we all want ActiveRecord...
  • 10. Spiff uses Mongoid class Post include Mongoid::Document field :title, :type => String field :body, :type => String end @posts = @db.collection('posts') @document = {:title => "MongoDB on Rails", :body => "Revelatory! Loved it!"} @posts.save(@document)
  • 11. Associations in Mongoid class Post include Mongoid::Document field :title, :type => String field :body, :type => String has_many :comments end class Comment include Mongoid::Document field :rant, :type => String belongs_to :post, :inverse_of => :comments end This creates an Embedded Document. @posts = @db.collection('posts') @document = {:title => "MongoDB on Rails", :body => "Revelatory! Loved it!", :comments => [{:rant => “I completely disagree”}] } @posts.save(@document)
  • 12. Keys, Validations, Timestamps & Hooks class Post include Mongoid::Document include Mongoid::Timestamps field :title, :type => String field :body, :type => String field :slug, :type => String has_many :comments has_key :title, :unique => true # “Audi IMS” becomes “audiims” validates_presence_of :title, :body validates_unqiueness_of :title before_save :set_slug def set_slug self.slug = “#{title.parameterize}-#{body[0..3]}” end end
  • 13. Versioning a Mongo Document class Post include Mongoid::Document include Mongoid::Timestamps include Mongoid::Versioning field :title, :type => String field :body, :type => String field :slug, :type => String has_many :comments has_key :title, :unique => true # “Audi IMS” becomes “audiims” validates_presence_of :title, :body validates_unqiueness_of :title before_save :set_slug def set_slug self.slug = “#{title.parameterize}-#{body[0..3]}” end end
  • 14. Access related items class Post include Mongoid::Document include Mongoid::Timestamps include Mongoid::Versioning field :title, :type => String field :body, :type => String field :slug, :type => String has_many :comments belongs_to_related :account has_many_related :sources ..... end database.yml meet database.mongo.yml
  • 15. But does it blend? Post.all(:conditions => { :title => “Rails 2.3” }) Post.find(:all, ...) Post.first(...) Post.find_or_create_by(:title => “Merb is dead”) Post.find_or_initialize_by(...) Associations: @post.comments.all
  • 16. fuck SQL! Criteria is the shit. Criteria#all - perform exact matches Post.criteria.all(:title => [ “Rails”, “2.3” ]) Criteria#find - match key/value Post.criteria.and(:created_at.gt => 2.months.ago) Criteria#exclude Post.criteria.exclude(:created_at => Date.today) Criteria#id - match document id Post.criteria.id(“4b2fe28ee2dc9b5f7b000029”) Criteria#in - match any of the values in an array Post.criteria.in(:title => [“Merb”, “Rails”, “Ruby”] Criteria#order_by Post.criteria.order_by([[:created_at, :desc], [:title, :asc] ]) Criteria also has #limit, #not_in, #only, #skip
  • 17. arithmetic, grouping & aggregation #max, #min, #sum, #aggregate, #group
  • 18. “But what about named scopes dude?!” -Gabe named_scope :active, criteria.where(:active => true) do def count size end end named_scope :inactive, :where => { :active => false } named_scope :frags_over, lambda { |count| { :where => { :frags.gt => count } } } named_scope :deaths_under, lambda { |count| criteria.where(:deaths.lt => count) }
  • 19. You can chain any of the Criteria API Post.in(:title => [“Rails”, “Ruby”]).where(:created_at.gt => 2.months.ago).skip(10) class Post include Mongoid::Document class << self def ruby_related criteria.in(:title => [“Ruby”, “Rails”]) end def in_last_two_months criteria.where(:created_at.gt => 2.months.ago)) end end end Post.ruby_related.in_last_two_months
  • 20. additional mongoid features Composite Keys Indexing Inheritance native MongoDB expressions