SlideShare ist ein Scribd-Unternehmen logo
1 von 45
SOMETHING SOMETHING
                     MONGO
                           Introduction to MongoDB
            Persisting dynamic data with MongoDB, MongoMapper &
                               metaprogramming




Saturday 1 May 2010
1
                                                                            2
                                                                            3
                                                                            4
                                                                            5
                                                                            6
                                                                            7
    • Bernard            Grymonpon




                                                                            8
                                                                            9
                                                                            10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
    • Openminds              BVBA

    • Rails           Hosting & Rails-shop            ribbit




    • @wonko_be              - @openminds_be


                                               Top sites deserve
                                               maximum uptime

                                               openminds.be
                                               tailored hosting solutions


Saturday 1 May 2010
Saturday 1 May 2010
WHAT IS IT?


    • Document-based               data store

    • JSON-style            data (BSON)

    • Built           for speed (searching)

    • Massive            amounts of data (humongous)



Saturday 1 May 2010
SCALING



    • Has             built in High Availability (Replication and Failover)

    • Has             built in Auto-sharding




Saturday 1 May 2010
SPEED


    • GridFS          as document store

    • In-place        updates

    • Indexes




Saturday 1 May 2010
QUERYING


    • rich        syntax

    • sorting           (order by), skipping (limit)

    • field            selection

    • mapreduce              (group by)



Saturday 1 May 2010
SCHEMALESS

    • No         fixed set of fields when storing an document

         • title: “foo”, author: “bar”

         • title: “arrrr”, author: “captain”, when: “today”

    • We          get empty fields when selecting non-existing data

         • find        will return “when” as empty when selecting all data


Saturday 1 May 2010
USE...

                      YES                          NO

    • (most) Websites          • Transactions

    • Caching                  • Lots   of joins

    • Scalabilty               • Fixed   datasets (science,...)




Saturday 1 May 2010
START USING IT
    • MongoDB           in google: www.mongodb.org - Quickstart

         • make       a directory

         • download       mongodb

         • unpack




Saturday 1 May 2010
START USING IT




Saturday 1 May 2010
START USING IT




Saturday 1 May 2010
QUERYING

           > db.arrrrcamp.save({talk: "MongoDB", who: "Bernard"})
           > db.arrrrcamp.find()
           {
             "_id" : ObjectId("4b681a1ecf1bcfea49f4b2ae"),
             "talk" : "MongoDB",
             "who" : "Bernard"
           }



Saturday 1 May 2010
MORE QUERYING

           > db.arrrrcamp.find({who: "Bernard")
           {
             "_id" : ObjectId("4b681a1ecf1bcfea49f4b2ae"),
             "talk" : "MongoDB",
             "who" : "Bernard"
           }




Saturday 1 May 2010
MORE QUERYING




Saturday 1 May 2010
Saturday 1 May 2010
Saturday 1 May 2010
gem install mongo_mapper




Saturday 1 May 2010
gem install mongo_mapper
                        gem install mongo_ext




Saturday 1 May 2010
require 'mongo_mapper'
                      MongoMapper.database = ‘arrrrcamp’




Saturday 1 May 2010
class Presenter
                        include MongoMapper::Document
                      end




Saturday 1 May 2010
class Presenter
                        include MongoMapper::Document

                       key :name, String
                       key :confirmed, Boolean
                       key :keywords, Array
                       key :presentation, Presentation
                      end




Saturday 1 May 2010
presenter = Presenter.new({
                        :name => “Bernard”,
                        :confirmed => true,
                        :keywords => [“Openminds”, “geek”]
                      })
                      presenter.save
                      presenter.destroy




Saturday 1 May 2010
EMBEDDED DOCUMENT


                      include MongoMapper::EmbeddedDocument




Saturday 1 May 2010
ACTIVERECORD, ANYONE?




Saturday 1 May 2010
MONGOMAPPER HAS


    • validates_*

    • before_save        / after_update / ...

    • has_many         / belongs_to

    • timestamps!




Saturday 1 May 2010
STORING CUSTOM
                              DATATYPES

    • to_mongo     - serialize your own data to a known mongo-
        storable data structure (string, array,...)

    • from_mongo              - unserialize your data and return an object (of
        “self ”)

    • both            are class methods (!)



Saturday 1 May 2010
class Keywords
     def initialize(array)
        @words = array
     end

       def to_a
         @words
       end

       class << self
         def to_mongo(value)
            value.is_a?(Keywords) ? value.to_a : value
         end

       def from_mongo(value)
         value ? self.new(value) : nil
       end
     end
   end
Saturday 1 May 2010
class Presenter
                   include MongoMapper::Document
                   key :keywords, Keywords
                 end




Saturday 1 May 2010
DYNAMIC DATA




Saturday 1 May 2010
INHERITANCE

                class Page                 class BlogPost < Page
                  key :permalink, String     key :content, String
                  key :title, String         has_many :comments
                end                        end

                                           class Redirect < Page
                                             key :destination, String
                                           end

Saturday 1 May 2010
MODULAR
                      module Authentication
                       def self.included(base)
                         base.key :password, String
                         base.key :salt, String
                         base.key :login, String
                       end
                      end

                      class Person
                        include MongoMapper::Document
                        include Authentication
                      end
Saturday 1 May 2010
MULTISITE WEBSHOP
                          EXAMPLE
                         per instance data gathering




Saturday 1 May 2010
WHAT TO BUILD


    • Ordering            system - multiple stores: shoes, tv’s, mobile phones

    • One             system

    • Each            shop has its own fields to require for an order




Saturday 1 May 2010
SOLUTION



    • metaprogramming: dynamically     generate a class for each site

    • dynamically     add the fields to the mongomapper




Saturday 1 May 2010
SITE-CLASS


    • Can             be a Mongo-document

    • Can             be an ActiveRecord object

    • Can             be a (Rails 3) ActiveModel object (REST?)

    • Has             to “respond_to? :id” and “respond_to? :order_fields”



Saturday 1 May 2010
ORDER CLASS: MM

    class Order
     include MongoMapper::Document
     key :order_id, String
    end



Saturday 1 May 2010
FACTORY-PATTERN
    class Order

        class << self
          def for_site(site)
            klass = Class.new(self)
            klass.order_fields = site.order_fields
            Object.const_set("OrderForSite#{site.id}", klass)
            klass
          end

     end
    end
Saturday 1 May 2010
DYNAMIC DOCUMENT
                          BUILDING

    class Order
      def order_fields=(fields)
         fields.each do |field|
           key field, String
       end
      end
    end

Saturday 1 May 2010
class Order
      include MongoMapper::Document
      key :order_id, String

        class << self
          def for_site(site)
             klass = Class.new(self)
             klass.order_fields = site.order_fields
             Object.const_set("OrderForSite#{site.id}", klass)
             klass
          end

        def order_fields=(fields)
          fields.each do |field|
            key field, String
          end
        end
      end
    end
Saturday 1 May 2010
TRY IT OUT


         current_site.order_fields
         #=> [“field1”, “field2”]
         @order = Order.for_site(current_site).new
         #=> #<OrderForSite2172858380 field1: nil, field2: nil,
         order_id: nil>



Saturday 1 May 2010
Saturday 1 May 2010
Saturday 1 May 2010
Saturday 1 May 2010
Q&A




Saturday 1 May 2010

Weitere ähnliche Inhalte

Ähnlich wie Persisting dynamic data with mongodb and mongomapper

BRAINREPUBLIC - Powered by no-SQL
BRAINREPUBLIC - Powered by no-SQLBRAINREPUBLIC - Powered by no-SQL
BRAINREPUBLIC - Powered by no-SQLAndreas Jung
 
Ruby on CouchDB - SimplyStored and RockingChair
Ruby on CouchDB - SimplyStored and RockingChairRuby on CouchDB - SimplyStored and RockingChair
Ruby on CouchDB - SimplyStored and RockingChairJonathan Weiss
 
MongoDB: a gentle, friendly overview
MongoDB: a gentle, friendly overviewMongoDB: a gentle, friendly overview
MongoDB: a gentle, friendly overviewAntonio Pintus
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBRavi Teja
 
Mongo NYC PHP Development
Mongo NYC PHP Development Mongo NYC PHP Development
Mongo NYC PHP Development Fitz Agard
 
Apache Solr for TYPO3 (@ T3CON10 Dallas, TX)
Apache Solr for TYPO3 (@ T3CON10 Dallas, TX)Apache Solr for TYPO3 (@ T3CON10 Dallas, TX)
Apache Solr for TYPO3 (@ T3CON10 Dallas, TX)Ingo Renner
 
Using Mongomapper to store dynamic data
Using Mongomapper to store dynamic dataUsing Mongomapper to store dynamic data
Using Mongomapper to store dynamic datawonko
 
10gen MongoDB Video Presentation at WebGeek DevCup
10gen MongoDB Video Presentation at WebGeek DevCup10gen MongoDB Video Presentation at WebGeek DevCup
10gen MongoDB Video Presentation at WebGeek DevCupWebGeek Philippines
 
Mongo db with spring data document
Mongo db with spring data documentMongo db with spring data document
Mongo db with spring data documentSean Lee
 
OSDC 2012 | Building a first application on MongoDB by Ross Lawley
OSDC 2012 | Building a first application on MongoDB by Ross LawleyOSDC 2012 | Building a first application on MongoDB by Ross Lawley
OSDC 2012 | Building a first application on MongoDB by Ross LawleyNETWAYS
 
Bar Camp Auckland - Mongo DB Presentation BCA4
Bar Camp Auckland - Mongo DB Presentation BCA4Bar Camp Auckland - Mongo DB Presentation BCA4
Bar Camp Auckland - Mongo DB Presentation BCA4John Ballinger
 
My first moments with MongoDB
My first moments with MongoDBMy first moments with MongoDB
My first moments with MongoDBColin Charles
 
MongoDB NYC Python
MongoDB NYC PythonMongoDB NYC Python
MongoDB NYC PythonMike Dirolf
 
Groovy 1 7 Update, past, present, future - S2G Forum 2010
Groovy 1 7 Update, past, present, future - S2G Forum 2010Groovy 1 7 Update, past, present, future - S2G Forum 2010
Groovy 1 7 Update, past, present, future - S2G Forum 2010Guillaume Laforge
 
Rapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodbRapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodbikailan
 

Ähnlich wie Persisting dynamic data with mongodb and mongomapper (20)

BRAINREPUBLIC - Powered by no-SQL
BRAINREPUBLIC - Powered by no-SQLBRAINREPUBLIC - Powered by no-SQL
BRAINREPUBLIC - Powered by no-SQL
 
MongoDB at RuPy
MongoDB at RuPyMongoDB at RuPy
MongoDB at RuPy
 
Everyday - mongodb
Everyday - mongodbEveryday - mongodb
Everyday - mongodb
 
Ruby on CouchDB - SimplyStored and RockingChair
Ruby on CouchDB - SimplyStored and RockingChairRuby on CouchDB - SimplyStored and RockingChair
Ruby on CouchDB - SimplyStored and RockingChair
 
MongoDB: a gentle, friendly overview
MongoDB: a gentle, friendly overviewMongoDB: a gentle, friendly overview
MongoDB: a gentle, friendly overview
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
mongoDB at Visibiz
mongoDB at VisibizmongoDB at Visibiz
mongoDB at Visibiz
 
Mongo NYC PHP Development
Mongo NYC PHP Development Mongo NYC PHP Development
Mongo NYC PHP Development
 
Apache Solr for TYPO3 (@ T3CON10 Dallas, TX)
Apache Solr for TYPO3 (@ T3CON10 Dallas, TX)Apache Solr for TYPO3 (@ T3CON10 Dallas, TX)
Apache Solr for TYPO3 (@ T3CON10 Dallas, TX)
 
Using Mongomapper to store dynamic data
Using Mongomapper to store dynamic dataUsing Mongomapper to store dynamic data
Using Mongomapper to store dynamic data
 
10gen MongoDB Video Presentation at WebGeek DevCup
10gen MongoDB Video Presentation at WebGeek DevCup10gen MongoDB Video Presentation at WebGeek DevCup
10gen MongoDB Video Presentation at WebGeek DevCup
 
Mongo db with spring data document
Mongo db with spring data documentMongo db with spring data document
Mongo db with spring data document
 
Couchdbkit & Dango
Couchdbkit & DangoCouchdbkit & Dango
Couchdbkit & Dango
 
OSDC 2012 | Building a first application on MongoDB by Ross Lawley
OSDC 2012 | Building a first application on MongoDB by Ross LawleyOSDC 2012 | Building a first application on MongoDB by Ross Lawley
OSDC 2012 | Building a first application on MongoDB by Ross Lawley
 
Bar Camp Auckland - Mongo DB Presentation BCA4
Bar Camp Auckland - Mongo DB Presentation BCA4Bar Camp Auckland - Mongo DB Presentation BCA4
Bar Camp Auckland - Mongo DB Presentation BCA4
 
My first moments with MongoDB
My first moments with MongoDBMy first moments with MongoDB
My first moments with MongoDB
 
MongoDB for Genealogy
MongoDB for GenealogyMongoDB for Genealogy
MongoDB for Genealogy
 
MongoDB NYC Python
MongoDB NYC PythonMongoDB NYC Python
MongoDB NYC Python
 
Groovy 1 7 Update, past, present, future - S2G Forum 2010
Groovy 1 7 Update, past, present, future - S2G Forum 2010Groovy 1 7 Update, past, present, future - S2G Forum 2010
Groovy 1 7 Update, past, present, future - S2G Forum 2010
 
Rapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodbRapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodb
 

Kürzlich hochgeladen

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 

Kürzlich hochgeladen (20)

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 

Persisting dynamic data with mongodb and mongomapper

  • 1. SOMETHING SOMETHING MONGO Introduction to MongoDB Persisting dynamic data with MongoDB, MongoMapper & metaprogramming Saturday 1 May 2010
  • 2. 1 2 3 4 5 6 7 • Bernard Grymonpon 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 • Openminds BVBA • Rails Hosting & Rails-shop ribbit • @wonko_be - @openminds_be Top sites deserve maximum uptime openminds.be tailored hosting solutions Saturday 1 May 2010
  • 4. WHAT IS IT? • Document-based data store • JSON-style data (BSON) • Built for speed (searching) • Massive amounts of data (humongous) Saturday 1 May 2010
  • 5. SCALING • Has built in High Availability (Replication and Failover) • Has built in Auto-sharding Saturday 1 May 2010
  • 6. SPEED • GridFS as document store • In-place updates • Indexes Saturday 1 May 2010
  • 7. QUERYING • rich syntax • sorting (order by), skipping (limit) • field selection • mapreduce (group by) Saturday 1 May 2010
  • 8. SCHEMALESS • No fixed set of fields when storing an document • title: “foo”, author: “bar” • title: “arrrr”, author: “captain”, when: “today” • We get empty fields when selecting non-existing data • find will return “when” as empty when selecting all data Saturday 1 May 2010
  • 9. USE... YES NO • (most) Websites • Transactions • Caching • Lots of joins • Scalabilty • Fixed datasets (science,...) Saturday 1 May 2010
  • 10. START USING IT • MongoDB in google: www.mongodb.org - Quickstart • make a directory • download mongodb • unpack Saturday 1 May 2010
  • 13. QUERYING > db.arrrrcamp.save({talk: "MongoDB", who: "Bernard"}) > db.arrrrcamp.find() { "_id" : ObjectId("4b681a1ecf1bcfea49f4b2ae"), "talk" : "MongoDB", "who" : "Bernard" } Saturday 1 May 2010
  • 14. MORE QUERYING > db.arrrrcamp.find({who: "Bernard") { "_id" : ObjectId("4b681a1ecf1bcfea49f4b2ae"), "talk" : "MongoDB", "who" : "Bernard" } Saturday 1 May 2010
  • 19. gem install mongo_mapper gem install mongo_ext Saturday 1 May 2010
  • 20. require 'mongo_mapper' MongoMapper.database = ‘arrrrcamp’ Saturday 1 May 2010
  • 21. class Presenter include MongoMapper::Document end Saturday 1 May 2010
  • 22. class Presenter include MongoMapper::Document key :name, String key :confirmed, Boolean key :keywords, Array key :presentation, Presentation end Saturday 1 May 2010
  • 23. presenter = Presenter.new({ :name => “Bernard”, :confirmed => true, :keywords => [“Openminds”, “geek”] }) presenter.save presenter.destroy Saturday 1 May 2010
  • 24. EMBEDDED DOCUMENT include MongoMapper::EmbeddedDocument Saturday 1 May 2010
  • 26. MONGOMAPPER HAS • validates_* • before_save / after_update / ... • has_many / belongs_to • timestamps! Saturday 1 May 2010
  • 27. STORING CUSTOM DATATYPES • to_mongo - serialize your own data to a known mongo- storable data structure (string, array,...) • from_mongo - unserialize your data and return an object (of “self ”) • both are class methods (!) Saturday 1 May 2010
  • 28. class Keywords def initialize(array) @words = array end def to_a @words end class << self def to_mongo(value) value.is_a?(Keywords) ? value.to_a : value end def from_mongo(value) value ? self.new(value) : nil end end end Saturday 1 May 2010
  • 29. class Presenter include MongoMapper::Document key :keywords, Keywords end Saturday 1 May 2010
  • 31. INHERITANCE class Page class BlogPost < Page key :permalink, String key :content, String key :title, String has_many :comments end end class Redirect < Page key :destination, String end Saturday 1 May 2010
  • 32. MODULAR module Authentication def self.included(base) base.key :password, String base.key :salt, String base.key :login, String end end class Person include MongoMapper::Document include Authentication end Saturday 1 May 2010
  • 33. MULTISITE WEBSHOP EXAMPLE per instance data gathering Saturday 1 May 2010
  • 34. WHAT TO BUILD • Ordering system - multiple stores: shoes, tv’s, mobile phones • One system • Each shop has its own fields to require for an order Saturday 1 May 2010
  • 35. SOLUTION • metaprogramming: dynamically generate a class for each site • dynamically add the fields to the mongomapper Saturday 1 May 2010
  • 36. SITE-CLASS • Can be a Mongo-document • Can be an ActiveRecord object • Can be a (Rails 3) ActiveModel object (REST?) • Has to “respond_to? :id” and “respond_to? :order_fields” Saturday 1 May 2010
  • 37. ORDER CLASS: MM class Order include MongoMapper::Document key :order_id, String end Saturday 1 May 2010
  • 38. FACTORY-PATTERN class Order class << self def for_site(site) klass = Class.new(self) klass.order_fields = site.order_fields Object.const_set("OrderForSite#{site.id}", klass) klass end end end Saturday 1 May 2010
  • 39. DYNAMIC DOCUMENT BUILDING class Order def order_fields=(fields) fields.each do |field| key field, String end end end Saturday 1 May 2010
  • 40. class Order include MongoMapper::Document key :order_id, String class << self def for_site(site) klass = Class.new(self) klass.order_fields = site.order_fields Object.const_set("OrderForSite#{site.id}", klass) klass end def order_fields=(fields) fields.each do |field| key field, String end end end end Saturday 1 May 2010
  • 41. TRY IT OUT current_site.order_fields #=> [“field1”, “field2”] @order = Order.for_site(current_site).new #=> #<OrderForSite2172858380 field1: nil, field2: nil, order_id: nil> Saturday 1 May 2010