SlideShare a Scribd company logo
1 of 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

More Related Content

Similar to 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
 

Similar to 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
 

Recently uploaded

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Recently uploaded (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

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