SlideShare une entreprise Scribd logo
1  sur  42
The Ruby /
MongoDB ecosystem
        Harold Giménez
   Mongo Boston - Sept 20, 2010
Harold Giménez
@hgimenez
thoughtbot, inc.
Why Ruby?
•   Expressiveness, Elegance
•   Powerful
•   Simple, flexible syntax
•   Open Source
•   Community
•   Library support: rubygems
...maybe too many
     libraries
mongo-ruby-driver
http://github.com/mongodb/mongo-ruby-driver
Start here
Closest to mongo’s lingo, almost-native query syntax


     require 'mongo'
     db     = Mongo::Connection.new.db('mongo-boston')
     people = db.collection('people')

     people.insert({'name'     => 'Harold',
                   'address' => {
                     'city' => 'Boston'
                   }
                })
     people.insert({'name' => 'Jack'})
     people.find('name' => 'Harold').to_a
     people.find('address.city' => 'Boston').to_a
Tools
        mongoid            Mongomatic

    MongoMapper           MongoODM



          connection, cursor, CRUD
              mongo-ruby-driver
mongoid
http://github.com/mongoid/mongoid
class Person
  include Mongoid::Document

 field :cool_dude, :type => Boolean, :default => false
 field :name
 field :age,       :type => Integer

 embeds_one :address

  validates_presence_of :name
end

class Address
  include Mongoid::Document

  field :city
  field :zip_code
  embedded_in :person, :inverse_of => :address
end
class Person
  include Mongoid::Document

 field :cool_dude, :type => Boolean, :default => false
 field :name
 field :age,       :type => Integer

 embeds_one :address
                                           embeds_many
                                         references_one
  validates_presence_of :name
                                        references_many
end
                                          referenced_in

class Address
  include Mongoid::Document

  field :city
  field :zip_code
  embedded_in :person, :inverse_of => :address
end
> me = Person.create!(:cool_dude => true)
Mongoid::Errors::Validations: Validation failed - Name can't be blank.

> me = Person.create(:name => 'Harold', :cool_dude => true)
 => #<Person name: "Harold", _id:
BSON::ObjectId('4c950d73fff2cb4262000007'), cool_dude: true>

> me.address = Address.new(:city => 'Boston')
 => #<Address city: "Boston", zip_code: nil, _id:
BSON::ObjectId('4c950d83fff2cb4262000008')>
> me.save


 {
     "_id" : ObjectId("4c950d73fff2cb4262000007"),
     "address" : { "_id" : ObjectId("4c950d83fff2cb4262000008"),
                    "city" : "Boston",
                    "zip_code" : null
                 },
     "name" : "Harold",
     "cool_dude" : true
 }
mongoid criteria
me             = Person.create(:name => 'Harold', :cool_dude => true)
another_harold = Person.create(:name => 'Harold')
someone_else   = Person.create(:name => 'Jack',   :cool_dude => true)

Person.where(:name      => 'Harold')
Person.where(:cool_dude => true)
Person.where(:name      => 'Harold').where(:cool_dude => true)

class Person
  def self.cool_dudes
    where(:cool_dude => true)
  end
  def self.harolds
    where(:name => 'Harold')
  end
end
Person.cool_dudes.harolds
Person.harolds.not_in("address.city" =>
["Boston"]).asc("address.city")Person.cool_dudes.only(:id).where("address.
city" => "Boston")
more querying
Person.all_in(:name => [ "Harold", "Ha, Lord!" ])
Person.any_in(:status => ["Single", "Divorced", "Separated"])
Person.any_of({ :name => "Harold" }, { :cool_dude => true })
Person.and(:name => "Harold", :cool_dude => false)
Person.excludes("address.city" => "Boston")
Person.limit(20)
Person.not_in(:name => ["Harold", "Jack"])
Person.where(:address.exists => true)
Person.where(:age.gt => 21)
Person.where(:age.gte => 21)
Person.where(:age.lt => 30)
Person.where(:age.lte => 30)
Mongoid::Paranoia
class Person
  include Mongoid::Document
  include Mongoid::Paranoia
end

person.delete    # person.deleted_at = Time.now
person.restore   # phew!
person.delete!
person.restore   # it's gone :(
cursor proxy
module Mongoid
  class Cursor
    include Enumerable
    OPERATIONS = [
      :close, :closed?, :count, :explain,
      :fields, :full_collection_name, :hint, :limit,
      :order, :query_options_hash, :query_opts, :selector,
      :skip, :snapshot, :sort, :timeout
    ]
    OPERATIONS.each do |name|
      define_method(name) { |*args| @cursor.send(name, *args) }
    end
    def each
      # ...
    end
    def next_document
      # ...
    end
    def to_a
      # ...
    end
  end
Enables caching vs. lazy loading of big datasets

Person.all.cache.each { |person| person.hug }


or
class Person
  include Mongoid::Document
  cache
end

Person.all.each { |person| person.hug }
ActiveModel under
the hood

ActiveModel::Conversion
ActiveModel::Naming
ActiveModel::Serialization
ActiveModel::MassAssignmentSecurity
ActiveModel::Translation
ActiveModel::Validation
ActiveModel::Callbacks
MongoMapper
http://github.com/jnunemaker/mongomapper
class Person
  include MongoMapper::Document
  key :cool_dude, Boolean, :default => false
  key :name,      String, :required => true
  key :age,       Integer

  one :address
end

class Address
  include MongoMapper::EmbeddedDocument

  key :city,     String
  key :zip_code, String
end
class Person
  include MongoMapper::Document
  key :cool_dude, Boolean, :default => false
  key :name,      String, :required => true
  key :age,       Integer

  one :address                               many
end                                       belongs_to

class Address
  include MongoMapper::EmbeddedDocument

  key :city,     String
  key :zip_code, String
end
class Person
  include MongoMapper::Document
  key :cool_dude, Boolean, :default => false
  key :name,      String, :required => true
  key :age,       Integer

  one :address
end

class Address
  include MongoMapper::EmbeddedDocument

  key :city,     String
  key :zip_code, String
end
class Person
  include MongoMapper::Document
  key :cool_dude, Boolean, :default => false
  key :name,      String, :required => true
  key :age,       Integer

  one :address
                                             Alternative
end
                                          validation syntax
class Address
  include MongoMapper::EmbeddedDocument

  key :city,     String
  key :zip_code, String
end
> me = Person.create!(:cool_dude => true)
MongoMapper::DocumentNotValid: Validation failed: Name can't be empty

> me = Person.create(:name => 'Harold', :cool_dude => true)
 => #<Person name: "Harold", _id:
BSON::ObjectId('4c9508fbfff2cb4096000007'), cool_dude: true>

> me.address = Address.new(:city => 'Boston')
 => #<Address city: "Boston", zip_code: nil, _id:
BSON::ObjectId('4c950911fff2cb4096000008')>
> me.save


 {
     "_id" : ObjectId("4c9508fbfff2cb4096000007"),
     "address" : { "_id" : ObjectId("4c950911fff2cb4096000008"),
                    "city" : "Boston",
                    "zip_code" : null
                 },
     "name" : "Harold",
     "cool_dude" : true
 }
Plugin architecture
module MongoMapper
  module Plugins
    def plugins
      @plugins ||= []
    end

    def plugin(mod)
      extend mod::ClassMethods     if mod.const_defined?(:ClassMethods)
      include mod::InstanceMethods if mod.const_defined?(:InstanceMethods)
      mod.configure(self)          if mod.respond_to?(:configure)
      plugins << mod
    end
  end
end                   associations, dirty, document
          dynamic_querying, embedded_document, equality
                indexes, logger modifiers, pagination
                   persistence, protected, querying
             safe, SCI, scopes, serialization, validations,
              and more (pretty much everything in MM)
Querying (plucky)
   Person.where(:address.exists => true).all
   Person.where(:age.gt => 21).limit(10).all
   Person.where(:age.gte => 21).all
   Person.where(:age.lt => 30).all
   Person.where(:age.lte => 30).all




    (       Similar to mongoid’s
            querying and scoping          )
       Except for no support for
      #not_in, #exists, #any_of
     and others found in mongoid
Notable difference:

                                                 mongoid                MongoMapper

                                                #<Mongoid::Criteria:
Person.where(:name => 'Harold')             0x101754bd8 @klass=Person, #<Plucky::Query name:
                                           @options={}, @documents=[], "Harold">
                                           @selector={:name=>"Harold"}>

                                                #<Mongoid::Criteria:
                                            0x101754bd8 @klass=Person,
Person.where(:name => 'Harold').all        @options={}, @documents=[],
                                                                        [#<Person name: "Harold"]

                                           @selector={:name=>"Harold"}>



Person.where(:name => 'Harold').all.to_a   [#<Person name: "Harold"] [#<Person name: "Harold"]




            or #each, #map, etc
cache_key

   class Person
     include MongoMapper::Document
   end

   Person.new.cache_key
     # => "Person/new"
   Person.create.cache_key
     # => "Person/4c9508fbfff2cb4096000007"
Custom data types
    class MongoSet
      def self.to_mongo(value)
        value.to_a
      end

      def self.from_mongo(value)
        Set.new(value || [])
      end
    end

    class Person
      include MongoMapper::Document
      key :aliases, MongoSet
    end
Typecasting

class Person
  include MongoMapper::Document
  key :friend_ids, Array, :typecast => 'ObjectId'
end

Person.new(:friend_ids => %w(4c950520fff2cb3fb9000004 
                             4c950558fff2cb3fb9000005 
                             4c950911fff2cb4096000008) )
Both MongoMapper
and Mongoid provide:
   #cache_key                              Cursor wrapper/cache
     plugins                               embraces ActiveModel
custom data types                     thorough query syntax abstraction
   typecasting        Persistance

                       Querying

                     Associations

                    Embedded Docs

                     Serialization

                    Dynamic Finders

                      Pagination

                        Scopes

                        Rails 3
Rails 2, you are...
                               ing
                             oy t
                           nn no
                        , a ’s
                      ly at
                     g h          re
                    u
                   e in t yw   he
                .th us an
              .. o
                   c ing
                    go                                 e!
MongoMapper                                          m
                                              d to
                                         .d ea
                                       ..

                     Mongoid
MongoODM
http://github.com/carlosparamio/mongo_odm


                 Mongomatic
         MongoMapper
    http://github.com/benmyles/mongomatic
A fresh look
Query chaining
Lazy loading
Validations
Callbacks
Rails integration


       Worth keeping an eye on!
Mongoid     MongoMapper




   Side by side!
Mongomatic   MongoODM
Number of Files

        300




        250




        200
                                                                      project
                                                                          mongoid
files




                                                                          MongoMapper
                                                                          mongomatic
        150
                                                                          MongoODM




        100




         50




         May−09   Aug−09    Nov−09         Feb−10   May−10   Aug−10
                                     day
Number of Lines


                  30000
number_of_lines




                                                                                   project
                                                                                       mongoid
                  20000
                                                                                       MongoMapper
                                                                                       mongomatic
                                                                                       MongoODM




                  10000




                      0


                     May−09   Aug−09     Nov−09         Feb−10   May−10   Aug−10
                                                  day
Number of Collaborators

                80




                60


                                                                             project
collaborators




                                                                                 mongoid
                                                                                 MongoMapper
                                                                                 mongomatic
                40
                                                                                 MongoODM




                20




                 0


                May−09    Aug−09   Nov−09         Feb−10   May−10   Aug−10
                                            day
Number of Commits


          1500




                                                                        project
          1000
                                                                            mongoid
commits




                                                                            MongoMapper
                                                                            mongomatic
                                                                            MongoODM




          500




            0



            May−09   Aug−09   Nov−09         Feb−10   May−10   Aug−10
                                       day
mongoid release cycle

             25




             20
prior_days




             15




             10




             5




             0


                  2.0.0.beta.102.0.0.beta1v0.0.1 v0.10.5v0.11.4v0.12.0 v0.2.5v0.3.2v0.4.2v0.4.8v0.5.2v0.5.7 v0.6.2v0.6.7 v0.7.2v0.7.7 v0.8.2v0.8.7 v0.9.11 v0.9.6v1.0.1v1.0.6v1.1.4 v1.2.13 v1.2.5v1.9.0
                   2.0.0.beta.11 2.0.0.beta11v0.10.2v0.11.1v0.11.7 v0.2.2v0.2.7v0.3.4v0.4.4v0.5.1v0.5.4v0.5.9v0.6.3v0.6.8 v0.7.3v0.7.8 v0.8.3v0.8.8 v0.9.12 v0.9.7v1.0.2v1.1.0v1.2.0 v1.2.14 v1.2.6v1.9.1
                    2.0.0.beta.12 2.0.0.beta2 v0.10.3v0.11.2v0.11.8 v0.2.3v0.3.0v0.4.0v0.4.5 v0.5.11 v0.5.8 v0.6.4v0.6.9 v0.7.4v0.7.9 v0.8.4v0.8.9 v0.9.2 v0.9.8v1.0.3v1.1.1v1.2.1 v1.2.15 v1.2.7v2.0.0
                      2.0.0.beta.13 2.0.0.beta7 v0.10.4v0.11.3v0.11.9 v0.2.4v0.3.1v0.4.1v0.4.7 v0.5.3 v0.6.0 v0.6.5v0.7.0 v0.7.5v0.8.0 v0.8.5v0.9.0 v0.9.3 v0.9.9v1.0.4v1.1.2 v1.2.11 v1.2.3v1.2.8
                       2.0.0.beta.14 2.0.0.beta8 v0.10.6v0.11.5 v0.2.0 v0.2.6v0.3.3v0.4.3v0.5.0 v0.5.5 v0.6.1 v0.6.6v0.7.1 v0.7.6v0.8.1 v0.8.6v0.9.1 v0.9.4 v1.0.0v1.0.5v1.1.3 v1.2.12 v1.2.4v1.2.9
                        2.0.0.beta.16 2.0.0.beta9 v0.11.0v0.11.6 v0.2.1
                          2.0.0.beta.17
                            2.0.0.beta.7
                             2.0.0.beta.8 v0.10.0
                              2.0.0.beta.9 v0.10.1
                                 2.0.0.beta10                                               v0.5.10 v0.5.6 v0.6.10     v0.7.10      v0.8.10      v0.9.10 v0.9.5                 v1.2.10 v1.2.2    v2.0.0.beta1
                                                                                                                                                                                                   v2.0.0.beta3
                                                                                                                                                                                                     v2.0.0.beta4
                                                                                                             tag
MongoMapper release cycle
             50




             40




             30
prior_days




             20




             10




             0


                  v0.1.0 v0.1.2 v0.3.0 v0.3.2 v0.3.4 v0.4.0 v0.4.2 v0.5.1 v0.5.3 v0.5.5 v0.5.7 v0.6.0 v0.6.10 v0.6.3 v0.6.5 v0.6.7 v0.6.9 v0.7.1 v0.7.3 v0.7.5 v0.8.0 v0.8.2 v0.8.4
                      v0.1.1 v0.2.0 v0.3.1 v0.3.3 v0.3.5 v0.4.1 v0.5.0 v0.5.2 v0.5.4 v0.5.6 v0.5.8 v0.6.1 v0.6.2 v0.6.4 v0.6.6 v0.6.8 v0.7.0 v0.7.2 v0.7.4 v0.7.6 v0.8.1 v0.8.3
                                                                                              tag
the end

Contenu connexe

Tendances

"Powerful Analysis with the Aggregation Pipeline (Tutorial)"
"Powerful Analysis with the Aggregation Pipeline (Tutorial)""Powerful Analysis with the Aggregation Pipeline (Tutorial)"
"Powerful Analysis with the Aggregation Pipeline (Tutorial)"
MongoDB
 
MongoDB Schema Design
MongoDB Schema DesignMongoDB Schema Design
MongoDB Schema Design
Alex Litvinok
 

Tendances (20)

Data Modeling for the Real World
Data Modeling for the Real WorldData Modeling for the Real World
Data Modeling for the Real World
 
Schema Design by Example ~ MongoSF 2012
Schema Design by Example ~ MongoSF 2012Schema Design by Example ~ MongoSF 2012
Schema Design by Example ~ MongoSF 2012
 
Json
JsonJson
Json
 
Json at work overview and ecosystem-v2.0
Json at work   overview and ecosystem-v2.0Json at work   overview and ecosystem-v2.0
Json at work overview and ecosystem-v2.0
 
"Powerful Analysis with the Aggregation Pipeline (Tutorial)"
"Powerful Analysis with the Aggregation Pipeline (Tutorial)""Powerful Analysis with the Aggregation Pipeline (Tutorial)"
"Powerful Analysis with the Aggregation Pipeline (Tutorial)"
 
Strongly Typed Languages and Flexible Schemas
Strongly Typed Languages and Flexible SchemasStrongly Typed Languages and Flexible Schemas
Strongly Typed Languages and Flexible Schemas
 
Webinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible SchemasWebinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible Schemas
 
Introduction towebmatrix
Introduction towebmatrixIntroduction towebmatrix
Introduction towebmatrix
 
MongoDB .local London 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local London 2019: Using Client Side Encryption in MongoDB 4.2MongoDB .local London 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local London 2019: Using Client Side Encryption in MongoDB 4.2
 
MongoDB .local Munich 2019: Aggregation Pipeline Power++: How MongoDB 4.2 Pip...
MongoDB .local Munich 2019: Aggregation Pipeline Power++: How MongoDB 4.2 Pip...MongoDB .local Munich 2019: Aggregation Pipeline Power++: How MongoDB 4.2 Pip...
MongoDB .local Munich 2019: Aggregation Pipeline Power++: How MongoDB 4.2 Pip...
 
MongoDB Schema Design
MongoDB Schema DesignMongoDB Schema Design
MongoDB Schema Design
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapper
 
Building a Scalable Inbox System with MongoDB and Java
Building a Scalable Inbox System with MongoDB and JavaBuilding a Scalable Inbox System with MongoDB and Java
Building a Scalable Inbox System with MongoDB and Java
 
MongoDB Advanced Schema Design - Inboxes
MongoDB Advanced Schema Design - InboxesMongoDB Advanced Schema Design - Inboxes
MongoDB Advanced Schema Design - Inboxes
 
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
 
Json
JsonJson
Json
 
Agile Schema Design: An introduction to MongoDB
Agile Schema Design: An introduction to MongoDBAgile Schema Design: An introduction to MongoDB
Agile Schema Design: An introduction to MongoDB
 
MongoDB Europe 2016 - Debugging MongoDB Performance
MongoDB Europe 2016 - Debugging MongoDB PerformanceMongoDB Europe 2016 - Debugging MongoDB Performance
MongoDB Europe 2016 - Debugging MongoDB Performance
 
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial IndexesBack to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
 
MongoDB .local Munich 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB .local Munich 2019: Tips and Tricks++ for Querying and Indexing MongoDBMongoDB .local Munich 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB .local Munich 2019: Tips and Tricks++ for Querying and Indexing MongoDB
 

En vedette

Building Your First App with MongoDB
Building Your First App with MongoDBBuilding Your First App with MongoDB
Building Your First App with MongoDB
MongoDB
 
Mongo Seattle - The Business of MongoDB
Mongo Seattle - The Business of MongoDBMongo Seattle - The Business of MongoDB
Mongo Seattle - The Business of MongoDB
Justin Smestad
 
MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010
Eliot Horowitz
 
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB
 

En vedette (20)

Building Your First App with MongoDB
Building Your First App with MongoDBBuilding Your First App with MongoDB
Building Your First App with MongoDB
 
Mongodb and Totsy: An e-commerce case study
Mongodb and Totsy: An e-commerce case studyMongodb and Totsy: An e-commerce case study
Mongodb and Totsy: An e-commerce case study
 
MongoDB World 2016: Poster Sessions eBook
MongoDB World 2016: Poster Sessions eBookMongoDB World 2016: Poster Sessions eBook
MongoDB World 2016: Poster Sessions eBook
 
Mongo Seattle - The Business of MongoDB
Mongo Seattle - The Business of MongoDBMongo Seattle - The Business of MongoDB
Mongo Seattle - The Business of MongoDB
 
PHP, Lithium and MongoDB
PHP, Lithium and MongoDBPHP, Lithium and MongoDB
PHP, Lithium and MongoDB
 
MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010MongoDB Java Development - MongoBoston 2010
MongoDB Java Development - MongoBoston 2010
 
Webinar: Introducing the MongoDB Connector for BI 2.0 with Tableau
Webinar: Introducing the MongoDB Connector for BI 2.0 with TableauWebinar: Introducing the MongoDB Connector for BI 2.0 with Tableau
Webinar: Introducing the MongoDB Connector for BI 2.0 with Tableau
 
How Auto Trader enables the UK's largest digital automotive marketplace
How Auto Trader enables the UK's largest digital automotive marketplaceHow Auto Trader enables the UK's largest digital automotive marketplace
How Auto Trader enables the UK's largest digital automotive marketplace
 
The importance of efficient data management for Digital Transformation
The importance of efficient data management for Digital TransformationThe importance of efficient data management for Digital Transformation
The importance of efficient data management for Digital Transformation
 
Back to Basics: My First MongoDB Application
Back to Basics: My First MongoDB ApplicationBack to Basics: My First MongoDB Application
Back to Basics: My First MongoDB Application
 
Webinar: Transitioning from SQL to MongoDB
Webinar: Transitioning from SQL to MongoDBWebinar: Transitioning from SQL to MongoDB
Webinar: Transitioning from SQL to MongoDB
 
Back to Basics Webinar 3: Introduction to Replica Sets
Back to Basics Webinar 3: Introduction to Replica SetsBack to Basics Webinar 3: Introduction to Replica Sets
Back to Basics Webinar 3: Introduction to Replica Sets
 
Back to Basics 2017: Introduction to Sharding
Back to Basics 2017: Introduction to ShardingBack to Basics 2017: Introduction to Sharding
Back to Basics 2017: Introduction to Sharding
 
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
 
Back to Basics Webinar 1: Introduction to NoSQL
Back to Basics Webinar 1: Introduction to NoSQLBack to Basics Webinar 1: Introduction to NoSQL
Back to Basics Webinar 1: Introduction to NoSQL
 
Creating a Modern Data Architecture for Digital Transformation
Creating a Modern Data Architecture for Digital TransformationCreating a Modern Data Architecture for Digital Transformation
Creating a Modern Data Architecture for Digital Transformation
 
The Rise of Microservices
The Rise of MicroservicesThe Rise of Microservices
The Rise of Microservices
 
Webinar: Working with Graph Data in MongoDB
Webinar: Working with Graph Data in MongoDBWebinar: Working with Graph Data in MongoDB
Webinar: Working with Graph Data in MongoDB
 
MongoDB Days Silicon Valley: Implementing Graph Databases with MongoDB
MongoDB Days Silicon Valley: Implementing Graph Databases with MongoDBMongoDB Days Silicon Valley: Implementing Graph Databases with MongoDB
MongoDB Days Silicon Valley: Implementing Graph Databases with MongoDB
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB Application
 

Similaire à The Ruby/mongoDB ecosystem

NoSQL を Ruby で実践するための n 個の方法
NoSQL を Ruby で実践するための n 個の方法NoSQL を Ruby で実践するための n 個の方法
NoSQL を Ruby で実践するための n 個の方法
Tomohiro Nishimura
 
Mongoid in the real world
Mongoid in the real worldMongoid in the real world
Mongoid in the real world
Kevin Faustino
 
Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)
MongoSF
 

Similaire à The Ruby/mongoDB ecosystem (20)

NoSQL を Ruby で実践するための n 個の方法
NoSQL を Ruby で実践するための n 個の方法NoSQL を Ruby で実践するための n 個の方法
NoSQL を Ruby で実践するための n 個の方法
 
ActiveRecord vs Mongoid
ActiveRecord vs MongoidActiveRecord vs Mongoid
ActiveRecord vs Mongoid
 
Simple MongoDB design for Rails apps
Simple MongoDB design for Rails appsSimple MongoDB design for Rails apps
Simple MongoDB design for Rails apps
 
DataMapper @ RubyEnRails2009
DataMapper @ RubyEnRails2009DataMapper @ RubyEnRails2009
DataMapper @ RubyEnRails2009
 
Mongoid in the real world
Mongoid in the real worldMongoid in the real world
Mongoid in the real world
 
Datamapper @ Railsconf2010
Datamapper @ Railsconf2010Datamapper @ Railsconf2010
Datamapper @ Railsconf2010
 
Webinar: Back to Basics: Thinking in Documents
Webinar: Back to Basics: Thinking in DocumentsWebinar: Back to Basics: Thinking in Documents
Webinar: Back to Basics: Thinking in Documents
 
Webinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev TeamsWebinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev Teams
 
MongoMapper lightning talk
MongoMapper lightning talkMongoMapper lightning talk
MongoMapper lightning talk
 
MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011
 
MongoDB Europe 2016 - Graph Operations with MongoDB
MongoDB Europe 2016 - Graph Operations with MongoDBMongoDB Europe 2016 - Graph Operations with MongoDB
MongoDB Europe 2016 - Graph Operations with MongoDB
 
Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)
 
Webinar: Schema Design
Webinar: Schema DesignWebinar: Schema Design
Webinar: Schema Design
 
Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling
 
MongoDB - Introduction
MongoDB - IntroductionMongoDB - Introduction
MongoDB - Introduction
 
Python With MongoDB in advanced Python.pptx
Python With MongoDB in advanced Python.pptxPython With MongoDB in advanced Python.pptx
Python With MongoDB in advanced Python.pptx
 
Python With MongoDB.pptx
Python With MongoDB.pptxPython With MongoDB.pptx
Python With MongoDB.pptx
 
Mongodb mongoid
Mongodb mongoidMongodb mongoid
Mongodb mongoid
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Mongo Web Apps: OSCON 2011
Mongo Web Apps: OSCON 2011Mongo Web Apps: OSCON 2011
Mongo Web Apps: OSCON 2011
 

Dernier

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

The Ruby/mongoDB ecosystem

  • 1. The Ruby / MongoDB ecosystem Harold Giménez Mongo Boston - Sept 20, 2010
  • 3. Why Ruby? • Expressiveness, Elegance • Powerful • Simple, flexible syntax • Open Source • Community • Library support: rubygems
  • 4. ...maybe too many libraries
  • 5.
  • 7. Start here Closest to mongo’s lingo, almost-native query syntax require 'mongo' db = Mongo::Connection.new.db('mongo-boston') people = db.collection('people') people.insert({'name' => 'Harold', 'address' => { 'city' => 'Boston' } }) people.insert({'name' => 'Jack'}) people.find('name' => 'Harold').to_a people.find('address.city' => 'Boston').to_a
  • 8. Tools mongoid Mongomatic MongoMapper MongoODM connection, cursor, CRUD mongo-ruby-driver
  • 10. class Person include Mongoid::Document field :cool_dude, :type => Boolean, :default => false field :name field :age, :type => Integer embeds_one :address validates_presence_of :name end class Address include Mongoid::Document field :city field :zip_code embedded_in :person, :inverse_of => :address end
  • 11. class Person include Mongoid::Document field :cool_dude, :type => Boolean, :default => false field :name field :age, :type => Integer embeds_one :address embeds_many references_one validates_presence_of :name references_many end referenced_in class Address include Mongoid::Document field :city field :zip_code embedded_in :person, :inverse_of => :address end
  • 12. > me = Person.create!(:cool_dude => true) Mongoid::Errors::Validations: Validation failed - Name can't be blank. > me = Person.create(:name => 'Harold', :cool_dude => true) => #<Person name: "Harold", _id: BSON::ObjectId('4c950d73fff2cb4262000007'), cool_dude: true> > me.address = Address.new(:city => 'Boston') => #<Address city: "Boston", zip_code: nil, _id: BSON::ObjectId('4c950d83fff2cb4262000008')> > me.save { "_id" : ObjectId("4c950d73fff2cb4262000007"), "address" : { "_id" : ObjectId("4c950d83fff2cb4262000008"), "city" : "Boston", "zip_code" : null }, "name" : "Harold", "cool_dude" : true }
  • 13. mongoid criteria me = Person.create(:name => 'Harold', :cool_dude => true) another_harold = Person.create(:name => 'Harold') someone_else = Person.create(:name => 'Jack', :cool_dude => true) Person.where(:name => 'Harold') Person.where(:cool_dude => true) Person.where(:name => 'Harold').where(:cool_dude => true) class Person def self.cool_dudes where(:cool_dude => true) end def self.harolds where(:name => 'Harold') end end Person.cool_dudes.harolds Person.harolds.not_in("address.city" => ["Boston"]).asc("address.city")Person.cool_dudes.only(:id).where("address. city" => "Boston")
  • 14. more querying Person.all_in(:name => [ "Harold", "Ha, Lord!" ]) Person.any_in(:status => ["Single", "Divorced", "Separated"]) Person.any_of({ :name => "Harold" }, { :cool_dude => true }) Person.and(:name => "Harold", :cool_dude => false) Person.excludes("address.city" => "Boston") Person.limit(20) Person.not_in(:name => ["Harold", "Jack"]) Person.where(:address.exists => true) Person.where(:age.gt => 21) Person.where(:age.gte => 21) Person.where(:age.lt => 30) Person.where(:age.lte => 30)
  • 15. Mongoid::Paranoia class Person include Mongoid::Document include Mongoid::Paranoia end person.delete # person.deleted_at = Time.now person.restore # phew! person.delete! person.restore # it's gone :(
  • 16. cursor proxy module Mongoid class Cursor include Enumerable OPERATIONS = [ :close, :closed?, :count, :explain, :fields, :full_collection_name, :hint, :limit, :order, :query_options_hash, :query_opts, :selector, :skip, :snapshot, :sort, :timeout ] OPERATIONS.each do |name| define_method(name) { |*args| @cursor.send(name, *args) } end def each # ... end def next_document # ... end def to_a # ... end end
  • 17. Enables caching vs. lazy loading of big datasets Person.all.cache.each { |person| person.hug } or class Person include Mongoid::Document cache end Person.all.each { |person| person.hug }
  • 20. class Person include MongoMapper::Document key :cool_dude, Boolean, :default => false key :name, String, :required => true key :age, Integer one :address end class Address include MongoMapper::EmbeddedDocument key :city, String key :zip_code, String end
  • 21. class Person include MongoMapper::Document key :cool_dude, Boolean, :default => false key :name, String, :required => true key :age, Integer one :address many end belongs_to class Address include MongoMapper::EmbeddedDocument key :city, String key :zip_code, String end
  • 22. class Person include MongoMapper::Document key :cool_dude, Boolean, :default => false key :name, String, :required => true key :age, Integer one :address end class Address include MongoMapper::EmbeddedDocument key :city, String key :zip_code, String end
  • 23. class Person include MongoMapper::Document key :cool_dude, Boolean, :default => false key :name, String, :required => true key :age, Integer one :address Alternative end validation syntax class Address include MongoMapper::EmbeddedDocument key :city, String key :zip_code, String end
  • 24. > me = Person.create!(:cool_dude => true) MongoMapper::DocumentNotValid: Validation failed: Name can't be empty > me = Person.create(:name => 'Harold', :cool_dude => true) => #<Person name: "Harold", _id: BSON::ObjectId('4c9508fbfff2cb4096000007'), cool_dude: true> > me.address = Address.new(:city => 'Boston') => #<Address city: "Boston", zip_code: nil, _id: BSON::ObjectId('4c950911fff2cb4096000008')> > me.save { "_id" : ObjectId("4c9508fbfff2cb4096000007"), "address" : { "_id" : ObjectId("4c950911fff2cb4096000008"), "city" : "Boston", "zip_code" : null }, "name" : "Harold", "cool_dude" : true }
  • 25. Plugin architecture module MongoMapper module Plugins def plugins @plugins ||= [] end def plugin(mod) extend mod::ClassMethods if mod.const_defined?(:ClassMethods) include mod::InstanceMethods if mod.const_defined?(:InstanceMethods) mod.configure(self) if mod.respond_to?(:configure) plugins << mod end end end associations, dirty, document dynamic_querying, embedded_document, equality indexes, logger modifiers, pagination persistence, protected, querying safe, SCI, scopes, serialization, validations, and more (pretty much everything in MM)
  • 26. Querying (plucky) Person.where(:address.exists => true).all Person.where(:age.gt => 21).limit(10).all Person.where(:age.gte => 21).all Person.where(:age.lt => 30).all Person.where(:age.lte => 30).all ( Similar to mongoid’s querying and scoping ) Except for no support for #not_in, #exists, #any_of and others found in mongoid
  • 27. Notable difference: mongoid MongoMapper #<Mongoid::Criteria: Person.where(:name => 'Harold') 0x101754bd8 @klass=Person, #<Plucky::Query name: @options={}, @documents=[], "Harold"> @selector={:name=>"Harold"}> #<Mongoid::Criteria: 0x101754bd8 @klass=Person, Person.where(:name => 'Harold').all @options={}, @documents=[], [#<Person name: "Harold"] @selector={:name=>"Harold"}> Person.where(:name => 'Harold').all.to_a [#<Person name: "Harold"] [#<Person name: "Harold"] or #each, #map, etc
  • 28. cache_key class Person include MongoMapper::Document end Person.new.cache_key # => "Person/new" Person.create.cache_key # => "Person/4c9508fbfff2cb4096000007"
  • 29. Custom data types class MongoSet def self.to_mongo(value) value.to_a end def self.from_mongo(value) Set.new(value || []) end end class Person include MongoMapper::Document key :aliases, MongoSet end
  • 30. Typecasting class Person include MongoMapper::Document key :friend_ids, Array, :typecast => 'ObjectId' end Person.new(:friend_ids => %w(4c950520fff2cb3fb9000004 4c950558fff2cb3fb9000005 4c950911fff2cb4096000008) )
  • 31. Both MongoMapper and Mongoid provide: #cache_key Cursor wrapper/cache plugins embraces ActiveModel custom data types thorough query syntax abstraction typecasting Persistance Querying Associations Embedded Docs Serialization Dynamic Finders Pagination Scopes Rails 3
  • 32. Rails 2, you are... ing oy t nn no , a ’s ly at g h re u e in t yw he .th us an .. o c ing go e! MongoMapper m d to .d ea .. Mongoid
  • 33. MongoODM http://github.com/carlosparamio/mongo_odm Mongomatic MongoMapper http://github.com/benmyles/mongomatic
  • 34. A fresh look Query chaining Lazy loading Validations Callbacks Rails integration Worth keeping an eye on!
  • 35. Mongoid MongoMapper Side by side! Mongomatic MongoODM
  • 36. Number of Files 300 250 200 project mongoid files MongoMapper mongomatic 150 MongoODM 100 50 May−09 Aug−09 Nov−09 Feb−10 May−10 Aug−10 day
  • 37. Number of Lines 30000 number_of_lines project mongoid 20000 MongoMapper mongomatic MongoODM 10000 0 May−09 Aug−09 Nov−09 Feb−10 May−10 Aug−10 day
  • 38. Number of Collaborators 80 60 project collaborators mongoid MongoMapper mongomatic 40 MongoODM 20 0 May−09 Aug−09 Nov−09 Feb−10 May−10 Aug−10 day
  • 39. Number of Commits 1500 project 1000 mongoid commits MongoMapper mongomatic MongoODM 500 0 May−09 Aug−09 Nov−09 Feb−10 May−10 Aug−10 day
  • 40. mongoid release cycle 25 20 prior_days 15 10 5 0 2.0.0.beta.102.0.0.beta1v0.0.1 v0.10.5v0.11.4v0.12.0 v0.2.5v0.3.2v0.4.2v0.4.8v0.5.2v0.5.7 v0.6.2v0.6.7 v0.7.2v0.7.7 v0.8.2v0.8.7 v0.9.11 v0.9.6v1.0.1v1.0.6v1.1.4 v1.2.13 v1.2.5v1.9.0 2.0.0.beta.11 2.0.0.beta11v0.10.2v0.11.1v0.11.7 v0.2.2v0.2.7v0.3.4v0.4.4v0.5.1v0.5.4v0.5.9v0.6.3v0.6.8 v0.7.3v0.7.8 v0.8.3v0.8.8 v0.9.12 v0.9.7v1.0.2v1.1.0v1.2.0 v1.2.14 v1.2.6v1.9.1 2.0.0.beta.12 2.0.0.beta2 v0.10.3v0.11.2v0.11.8 v0.2.3v0.3.0v0.4.0v0.4.5 v0.5.11 v0.5.8 v0.6.4v0.6.9 v0.7.4v0.7.9 v0.8.4v0.8.9 v0.9.2 v0.9.8v1.0.3v1.1.1v1.2.1 v1.2.15 v1.2.7v2.0.0 2.0.0.beta.13 2.0.0.beta7 v0.10.4v0.11.3v0.11.9 v0.2.4v0.3.1v0.4.1v0.4.7 v0.5.3 v0.6.0 v0.6.5v0.7.0 v0.7.5v0.8.0 v0.8.5v0.9.0 v0.9.3 v0.9.9v1.0.4v1.1.2 v1.2.11 v1.2.3v1.2.8 2.0.0.beta.14 2.0.0.beta8 v0.10.6v0.11.5 v0.2.0 v0.2.6v0.3.3v0.4.3v0.5.0 v0.5.5 v0.6.1 v0.6.6v0.7.1 v0.7.6v0.8.1 v0.8.6v0.9.1 v0.9.4 v1.0.0v1.0.5v1.1.3 v1.2.12 v1.2.4v1.2.9 2.0.0.beta.16 2.0.0.beta9 v0.11.0v0.11.6 v0.2.1 2.0.0.beta.17 2.0.0.beta.7 2.0.0.beta.8 v0.10.0 2.0.0.beta.9 v0.10.1 2.0.0.beta10 v0.5.10 v0.5.6 v0.6.10 v0.7.10 v0.8.10 v0.9.10 v0.9.5 v1.2.10 v1.2.2 v2.0.0.beta1 v2.0.0.beta3 v2.0.0.beta4 tag
  • 41. MongoMapper release cycle 50 40 30 prior_days 20 10 0 v0.1.0 v0.1.2 v0.3.0 v0.3.2 v0.3.4 v0.4.0 v0.4.2 v0.5.1 v0.5.3 v0.5.5 v0.5.7 v0.6.0 v0.6.10 v0.6.3 v0.6.5 v0.6.7 v0.6.9 v0.7.1 v0.7.3 v0.7.5 v0.8.0 v0.8.2 v0.8.4 v0.1.1 v0.2.0 v0.3.1 v0.3.3 v0.3.5 v0.4.1 v0.5.0 v0.5.2 v0.5.4 v0.5.6 v0.5.8 v0.6.1 v0.6.2 v0.6.4 v0.6.6 v0.6.8 v0.7.0 v0.7.2 v0.7.4 v0.7.6 v0.8.1 v0.8.3 tag

Notes de l'éditeur