SlideShare une entreprise Scribd logo
1  sur  42
MongoDB
Ruby friendly document storage that doesn’t rhyme with ouch.




                                                Dallas.rb
Wynn Netherland
     @pengwynn

   http://squeejee.com
http://locomotivation.com
Not every data problem looks like this
So why do so many databases look like this?
and this?
When are RDBMS less than ideal?
Your data is stored and retrieved mainly by primary key,
without complex joins.

You have a non-trivial amount of data, and the
thought of managing lots of RDBMS shards and
replication failure scenarios gives you the fear.

http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key-
value-stores/
Enter key value stores
Some of the players
Project Voldemort
Ringo
Scalaris
Kai
Dynomite
MemcacheDB
ThruDB
CouchDB
Cassandra
HBase
Hypertable
Tokyo Cabinet/Tyrant

http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key-value-stores/
Tokyo Cabinet:
Popular with Rubyists, Big in Japan
Go kick the tires
• Lightning fast
• Works best for at objects
• Tokyo Tyrant for network access


http://www.igvita.com/2009/02/13/tokyo-cabinet-beyond-key-value-
store/
More document-oriented solutions
CouchDB
Apache CouchDB is a distributed, fault-tolerant and
schema-free document-oriented database accessible
via a RESTful HTTP/JSON API.




http://couchdb.apache.org/
Erlang + Javascript
Map + reduce
Very cool
Plenty o’ Ruby to go around
Ruby libraries for CouchDB
• CouchRest
• Basic model
• RelaxDB
• CouchPotato
• CouchFoo
• ActiveCouch
http://www.slideshare.net/brianthecoder/couchdb
Throw out everything
you learned about DB design
SQL                                       CouchDB

            Prede ned, explicit schema                      Dynamic, implicit schema



                                                   Collection of named documents with varying
               Uniform tables of data
                                                                    structure


      Normalized. Objects spread across tables.   Denormalized. Docs usually self contained. Data
               Duplication reduced.                             often duplicated.


     Must know schema to read/write a complete
                                                         Must know only document name
                     object



         Dynamic queries of static schemas              Static queries of dynamic schemas




http://damienkatz.net/files/What is CouchDB.pdf
SQL                                       CouchDB

       Prede ned, explicit schema                      Dynamic, implicit schema



                                              Collection of named documents with varying
          Uniform tables of data
                                                               structure


 Normalized. Objects spread across tables.   Denormalized. Docs usually self contained. Data
          Duplication reduced.                             often duplicated.


Must know schema to read/write a complete
                                                    Must know only document name
                object



    Dynamic queries of static schemas         Static queries of dynamic schemas
In walks Mongo
INTRO
INTRO


• Built   For Speed

• Document/Collection     Oriented

• Dynamic    Queries and Indexes

• Replication   and Failover
GREAT FOR

• Websites

• Caching

• High   volume, low value

• High   scalability

• Storage   of program objects and json
NOT AS GREAT FOR


• Highly   transactional

• Ad-hoc    business intelligence

• Problems    requiring SQL
INSTALLATION


• mkdir   -p /data/db

• download    pre-built for OSX and unzip to /usr/local/

• cp   -R /usr/local/pathtomongo/bin /usr/local/bin
DATABASE



• same   concept as mysql

• made   up of collections
COLLECTION

• Think   table, but with no schema

• For   grouping documents into smaller query sets (speed)

• Eachtop level entity in your app would have its own collection
 (users, articles, etc.)

• Indexable   by one or more key
DOCUMENT


• Stored   in a collection, think record or row

• Can   have _id key that works like primary keys in MySQL

• Two   options for relationships: subdocument or db reference
STORAGE (BSON)

{ author: 'joe',
    created: Date('03-28-2009'),
    title: 'Yet another blog post',
    text: 'Here is the text...',
    tags: [ 'example', 'joe' ],
    comments: [ { author: 'jim', comment: 'I disagree' },
                { author: 'nancy', comment: 'Good post' }
    ]
}




http://www.mongodb.org/display/DOCS/BSON
THAT LOOKS LIKE JSON

Where’s the Ruby?
QUERYING

• db.collection.find({‘first_name’: ‘John’})     # finds all Johns

• db.collection.find({‘first_name’: /^J/})     # regex

• db.collection.find_first({‘_id’:1})   # finds first with _id of 1

• db.collection.find({‘age’: {‘$gt’: 21}})   # finds possible drinkers

• db.collection.find({‘author.first_name’:‘John’})     # subdocument

• db.collection.find({$where:‘this.age       >= 6 && this.age <= 18’})
MORE QUERYING

• $in, $nin, $all, $ne, $gt, $gte, $lt, $lte, $size, $where

• :fields   (like :select in active record)

• :limit, :offset   for pagination

• :sort   ascending or descending [[‘foo’, 1], [‘bar’, -1]]

• count    and group (uses map/reduce)
HOW DO YOU
           USE IT WITH RUBY

• mongo-ruby-driver   http://github.com/mongodb/mongo-ruby-
 driver

• activerecord adapter http://github.com/mongodb/
 activerecord-mongo-adapter

• mongorecord  http://github.com/mongodb/mongo-
 activerecord-ruby
NUNEMAPPER
               (MONGOMAPPER)

• Mongo     is not MySQL

• DSL    for modeling domain should also teach you Mongo

• It   sounded fun

• Almost    finished and sitting in private GitHub repo
FEATURES

• Typecasting                       • Create  and Update with
                                      single or multiple
• Callbacks(ActiveSupport
 Callbacks)                         • Delete and Destroy and _all
                                      counterparts
• Validations   (using my fork of
 validatable)                       • Find: id, ids, :all, :first, :last

• Connection  and database          • Associations      (incomplete)
 can differ per document
EXAMPLE
class User
  include MongoMapper::Document
  key :name, String, :required => true, :length => 5..100
  key :email, String, :required => true, :index => true
  key :age, Integer, :numeric => true
  key :active, Boolean, :default => true

  one :address
  many :articles
end

class Address
  include MongoMapper::Document
  key :street, String
  key :city, String
  key :state, String, :length => 2
  key :zip, Integer, :numeric => true, :length => 5
end
RANDOM AWESOMENESS

• Capped   collections (think memcache, actually used for
 replication)

• Upserts   db.collection.update({‘_id’:1}, {‘$inc’:{‘views’:1}})


• Multikeys   (think tagging and full text search)

• GridFS   and auto-sharding
John Nunemaker
http://orderedlist.com
  http://railstips.org

         Links
http://www.10gen.com
 http://mongodb.com
Wynn Netherland
     @pengwynn

   http://squeejee.com
http://locomotivation.com

Contenu connexe

Tendances

Tendances (20)

PhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHPPhpstudyTokyo MongoDB PHP CakePHP
PhpstudyTokyo MongoDB PHP CakePHP
 
CouchDB in The Room
CouchDB in The RoomCouchDB in The Room
CouchDB in The Room
 
CouchDB introduction
CouchDB introductionCouchDB introduction
CouchDB introduction
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
DrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and DrupalDrupalCon Chicago Practical MongoDB and Drupal
DrupalCon Chicago Practical MongoDB and Drupal
 
CouchDB
CouchDBCouchDB
CouchDB
 
Using MongoDB and a Relational Database at MongoDB Day
Using MongoDB and a Relational Database at MongoDB DayUsing MongoDB and a Relational Database at MongoDB Day
Using MongoDB and a Relational Database at MongoDB Day
 
Mongo db operations_v2
Mongo db operations_v2Mongo db operations_v2
Mongo db operations_v2
 
Scaling up and accelerating Drupal 8 with NoSQL
Scaling up and accelerating Drupal 8 with NoSQLScaling up and accelerating Drupal 8 with NoSQL
Scaling up and accelerating Drupal 8 with NoSQL
 
Scala with mongodb
Scala with mongodbScala with mongodb
Scala with mongodb
 
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorialsMongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
 
Dealing with Azure Cosmos DB
Dealing with Azure Cosmos DBDealing with Azure Cosmos DB
Dealing with Azure Cosmos DB
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
 
How do i Meet MongoDB
How do i Meet MongoDBHow do i Meet MongoDB
How do i Meet MongoDB
 
Connecting NodeJS & MongoDB
Connecting NodeJS & MongoDBConnecting NodeJS & MongoDB
Connecting NodeJS & MongoDB
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
Mysql
MysqlMysql
Mysql
 
MongoDB basics & Introduction
MongoDB basics & IntroductionMongoDB basics & Introduction
MongoDB basics & Introduction
 
djatoka for djummies
djatoka for djummiesdjatoka for djummies
djatoka for djummies
 
Top 10 frameworks of node js
Top 10 frameworks of node jsTop 10 frameworks of node js
Top 10 frameworks of node js
 

En vedette

MongoHQ (Jason McCay & Ben Wyrosdick)
MongoHQ (Jason McCay & Ben Wyrosdick)MongoHQ (Jason McCay & Ben Wyrosdick)
MongoHQ (Jason McCay & Ben Wyrosdick)
MongoSF
 
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
 
Practical Ruby Projects with MongoDB - Ruby Midwest
Practical Ruby Projects with MongoDB - Ruby MidwestPractical Ruby Projects with MongoDB - Ruby Midwest
Practical Ruby Projects with MongoDB - Ruby Midwest
Alex Sharp
 
MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)
MongoSF
 
Cosmic rays detection theory
Cosmic rays detection theoryCosmic rays detection theory
Cosmic rays detection theory
Lalit Pradhan
 
Cosmic Ray Presentation
Cosmic Ray PresentationCosmic Ray Presentation
Cosmic Ray Presentation
guest3aa2df
 

En vedette (17)

MongoHQ (Jason McCay & Ben Wyrosdick)
MongoHQ (Jason McCay & Ben Wyrosdick)MongoHQ (Jason McCay & Ben Wyrosdick)
MongoHQ (Jason McCay & Ben Wyrosdick)
 
Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)
 
MongoDB on Windows Azure
MongoDB on Windows AzureMongoDB on Windows Azure
MongoDB on Windows Azure
 
Magic in ruby
Magic in rubyMagic in ruby
Magic in ruby
 
Ruby objects
Ruby objectsRuby objects
Ruby objects
 
ZODB Tips and Tricks
ZODB Tips and TricksZODB Tips and Tricks
ZODB Tips and Tricks
 
Practical Ruby Projects with MongoDB - Ruby Midwest
Practical Ruby Projects with MongoDB - Ruby MidwestPractical Ruby Projects with MongoDB - Ruby Midwest
Practical Ruby Projects with MongoDB - Ruby Midwest
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)
 
Cosmic rays detection theory
Cosmic rays detection theoryCosmic rays detection theory
Cosmic rays detection theory
 
HTML Lecture Part 1 of 2
HTML Lecture Part 1 of 2HTML Lecture Part 1 of 2
HTML Lecture Part 1 of 2
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 
The Black Magic of Ruby Metaprogramming
The Black Magic of Ruby MetaprogrammingThe Black Magic of Ruby Metaprogramming
The Black Magic of Ruby Metaprogramming
 
Cosmic Ray Presentation
Cosmic Ray PresentationCosmic Ray Presentation
Cosmic Ray Presentation
 
physics lecture
physics lecturephysics lecture
physics lecture
 
MongoDB: How it Works
MongoDB: How it WorksMongoDB: How it Works
MongoDB: How it Works
 
Solid state physics - Crystalline Solids
Solid state physics - Crystalline SolidsSolid state physics - Crystalline Solids
Solid state physics - Crystalline Solids
 

Similaire à MongoDB - Ruby document store that doesn't rhyme with ouch

Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Db
chriskite
 
mongodb11 (1) (1).pptx
mongodb11 (1) (1).pptxmongodb11 (1) (1).pptx
mongodb11 (1) (1).pptx
RoopaR36
 
NoSQL: Why, When, and How
NoSQL: Why, When, and HowNoSQL: Why, When, and How
NoSQL: Why, When, and How
BigBlueHat
 
My Sql And Search At Craigslist
My Sql And Search At CraigslistMy Sql And Search At Craigslist
My Sql And Search At Craigslist
MySQLConference
 

Similaire à MongoDB - Ruby document store that doesn't rhyme with ouch (20)

Spring one2gx2010 spring-nonrelational_data
Spring one2gx2010 spring-nonrelational_dataSpring one2gx2010 spring-nonrelational_data
Spring one2gx2010 spring-nonrelational_data
 
Non Relational Databases
Non Relational DatabasesNon Relational Databases
Non Relational Databases
 
MongoDB
MongoDBMongoDB
MongoDB
 
JS App Architecture
JS App ArchitectureJS App Architecture
JS App Architecture
 
Mongodb my
Mongodb myMongodb my
Mongodb my
 
MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB
MongoDBMongoDB
MongoDB
 
Taming NoSQL with Spring Data
Taming NoSQL with Spring DataTaming NoSQL with Spring Data
Taming NoSQL with Spring Data
 
MongoDB at FrozenRails
MongoDB at FrozenRailsMongoDB at FrozenRails
MongoDB at FrozenRails
 
Intro To Mongo Db
Intro To Mongo DbIntro To Mongo Db
Intro To Mongo Db
 
mongodb11 (1) (1).pptx
mongodb11 (1) (1).pptxmongodb11 (1) (1).pptx
mongodb11 (1) (1).pptx
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introduction
 
NoSQL: Why, When, and How
NoSQL: Why, When, and HowNoSQL: Why, When, and How
NoSQL: Why, When, and How
 
Mongo Bb - NoSQL tutorial
Mongo Bb - NoSQL tutorialMongo Bb - NoSQL tutorial
Mongo Bb - NoSQL tutorial
 
Navigating NoSQL in cloudy skies
Navigating NoSQL in cloudy skiesNavigating NoSQL in cloudy skies
Navigating NoSQL in cloudy skies
 
Nosql seminar
Nosql seminarNosql seminar
Nosql seminar
 
My Sql And Search At Craigslist
My Sql And Search At CraigslistMy Sql And Search At Craigslist
My Sql And Search At Craigslist
 
Drop acid
Drop acidDrop acid
Drop acid
 
No SQL : Which way to go? Presented at DDDMelbourne 2015
No SQL : Which way to go?  Presented at DDDMelbourne 2015No SQL : Which way to go?  Presented at DDDMelbourne 2015
No SQL : Which way to go? Presented at DDDMelbourne 2015
 
NoSQL, which way to go?
NoSQL, which way to go?NoSQL, which way to go?
NoSQL, which way to go?
 

Plus de Wynn Netherland

Big Design Conference: CSS3
Big Design Conference: CSS3 Big Design Conference: CSS3
Big Design Conference: CSS3
Wynn Netherland
 

Plus de Wynn Netherland (11)

Accelerated Native Mobile Development with the Ti gem
Accelerated Native Mobile Development with the Ti gemAccelerated Native Mobile Development with the Ti gem
Accelerated Native Mobile Development with the Ti gem
 
Accelerated Stylesheets
Accelerated StylesheetsAccelerated Stylesheets
Accelerated Stylesheets
 
Your government is Mashed UP!
Your government is Mashed UP!Your government is Mashed UP!
Your government is Mashed UP!
 
Compass, Sass, and the Enlightened CSS Developer
Compass, Sass, and the Enlightened CSS DeveloperCompass, Sass, and the Enlightened CSS Developer
Compass, Sass, and the Enlightened CSS Developer
 
JSON and the APInauts
JSON and the APInautsJSON and the APInauts
JSON and the APInauts
 
Big Design Conference: CSS3
Big Design Conference: CSS3 Big Design Conference: CSS3
Big Design Conference: CSS3
 
America, your congress is Mashed UP!
America, your congress is Mashed UP!America, your congress is Mashed UP!
America, your congress is Mashed UP!
 
CSS Metaframeworks: King of all @media
CSS Metaframeworks: King of all @mediaCSS Metaframeworks: King of all @media
CSS Metaframeworks: King of all @media
 
Build An App Start A Movement
Build An App Start A MovementBuild An App Start A Movement
Build An App Start A Movement
 
Javascript And Ruby Frameworks
Javascript And Ruby FrameworksJavascript And Ruby Frameworks
Javascript And Ruby Frameworks
 
Free(ish) Tools For Virtual Teams
Free(ish) Tools For Virtual TeamsFree(ish) Tools For Virtual Teams
Free(ish) Tools For Virtual Teams
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

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
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
"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 ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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...
 

MongoDB - Ruby document store that doesn't rhyme with ouch

  • 1. MongoDB Ruby friendly document storage that doesn’t rhyme with ouch. Dallas.rb
  • 2. Wynn Netherland @pengwynn http://squeejee.com http://locomotivation.com
  • 3. Not every data problem looks like this
  • 4. So why do so many databases look like this?
  • 6. When are RDBMS less than ideal? Your data is stored and retrieved mainly by primary key, without complex joins. You have a non-trivial amount of data, and the thought of managing lots of RDBMS shards and replication failure scenarios gives you the fear. http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key- value-stores/
  • 8. Some of the players Project Voldemort Ringo Scalaris Kai Dynomite MemcacheDB ThruDB CouchDB Cassandra HBase Hypertable Tokyo Cabinet/Tyrant http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key-value-stores/
  • 9. Tokyo Cabinet: Popular with Rubyists, Big in Japan
  • 10. Go kick the tires • Lightning fast • Works best for at objects • Tokyo Tyrant for network access http://www.igvita.com/2009/02/13/tokyo-cabinet-beyond-key-value- store/
  • 12.
  • 13. CouchDB Apache CouchDB is a distributed, fault-tolerant and schema-free document-oriented database accessible via a RESTful HTTP/JSON API. http://couchdb.apache.org/
  • 17. Plenty o’ Ruby to go around
  • 18. Ruby libraries for CouchDB • CouchRest • Basic model • RelaxDB • CouchPotato • CouchFoo • ActiveCouch http://www.slideshare.net/brianthecoder/couchdb
  • 19. Throw out everything you learned about DB design
  • 20. SQL CouchDB Prede ned, explicit schema Dynamic, implicit schema Collection of named documents with varying Uniform tables of data structure Normalized. Objects spread across tables. Denormalized. Docs usually self contained. Data Duplication reduced. often duplicated. Must know schema to read/write a complete Must know only document name object Dynamic queries of static schemas Static queries of dynamic schemas http://damienkatz.net/files/What is CouchDB.pdf
  • 21. SQL CouchDB Prede ned, explicit schema Dynamic, implicit schema Collection of named documents with varying Uniform tables of data structure Normalized. Objects spread across tables. Denormalized. Docs usually self contained. Data Duplication reduced. often duplicated. Must know schema to read/write a complete Must know only document name object Dynamic queries of static schemas Static queries of dynamic schemas
  • 23.
  • 24. INTRO
  • 25. INTRO • Built For Speed • Document/Collection Oriented • Dynamic Queries and Indexes • Replication and Failover
  • 26. GREAT FOR • Websites • Caching • High volume, low value • High scalability • Storage of program objects and json
  • 27. NOT AS GREAT FOR • Highly transactional • Ad-hoc business intelligence • Problems requiring SQL
  • 28. INSTALLATION • mkdir -p /data/db • download pre-built for OSX and unzip to /usr/local/ • cp -R /usr/local/pathtomongo/bin /usr/local/bin
  • 29. DATABASE • same concept as mysql • made up of collections
  • 30. COLLECTION • Think table, but with no schema • For grouping documents into smaller query sets (speed) • Eachtop level entity in your app would have its own collection (users, articles, etc.) • Indexable by one or more key
  • 31. DOCUMENT • Stored in a collection, think record or row • Can have _id key that works like primary keys in MySQL • Two options for relationships: subdocument or db reference
  • 32. STORAGE (BSON) { author: 'joe', created: Date('03-28-2009'), title: 'Yet another blog post', text: 'Here is the text...', tags: [ 'example', 'joe' ], comments: [ { author: 'jim', comment: 'I disagree' }, { author: 'nancy', comment: 'Good post' } ] } http://www.mongodb.org/display/DOCS/BSON
  • 33. THAT LOOKS LIKE JSON Where’s the Ruby?
  • 34. QUERYING • db.collection.find({‘first_name’: ‘John’}) # finds all Johns • db.collection.find({‘first_name’: /^J/}) # regex • db.collection.find_first({‘_id’:1}) # finds first with _id of 1 • db.collection.find({‘age’: {‘$gt’: 21}}) # finds possible drinkers • db.collection.find({‘author.first_name’:‘John’}) # subdocument • db.collection.find({$where:‘this.age >= 6 && this.age <= 18’})
  • 35. MORE QUERYING • $in, $nin, $all, $ne, $gt, $gte, $lt, $lte, $size, $where • :fields (like :select in active record) • :limit, :offset for pagination • :sort ascending or descending [[‘foo’, 1], [‘bar’, -1]] • count and group (uses map/reduce)
  • 36. HOW DO YOU USE IT WITH RUBY • mongo-ruby-driver http://github.com/mongodb/mongo-ruby- driver • activerecord adapter http://github.com/mongodb/ activerecord-mongo-adapter • mongorecord http://github.com/mongodb/mongo- activerecord-ruby
  • 37. NUNEMAPPER (MONGOMAPPER) • Mongo is not MySQL • DSL for modeling domain should also teach you Mongo • It sounded fun • Almost finished and sitting in private GitHub repo
  • 38. FEATURES • Typecasting • Create and Update with single or multiple • Callbacks(ActiveSupport Callbacks) • Delete and Destroy and _all counterparts • Validations (using my fork of validatable) • Find: id, ids, :all, :first, :last • Connection and database • Associations (incomplete) can differ per document
  • 39. EXAMPLE class User include MongoMapper::Document key :name, String, :required => true, :length => 5..100 key :email, String, :required => true, :index => true key :age, Integer, :numeric => true key :active, Boolean, :default => true one :address many :articles end class Address include MongoMapper::Document key :street, String key :city, String key :state, String, :length => 2 key :zip, Integer, :numeric => true, :length => 5 end
  • 40. RANDOM AWESOMENESS • Capped collections (think memcache, actually used for replication) • Upserts db.collection.update({‘_id’:1}, {‘$inc’:{‘views’:1}}) • Multikeys (think tagging and full text search) • GridFS and auto-sharding
  • 41. John Nunemaker http://orderedlist.com http://railstips.org Links http://www.10gen.com http://mongodb.com
  • 42. Wynn Netherland @pengwynn http://squeejee.com http://locomotivation.com

Notes de l'éditeur

  1. High volume, lower value. No transactions. Drivers for several languages. All network based for speed (instead of REST). Uses BSON for storage of objects and for building queries. Binary-encoded serialization like JSON. Allows for some representations that JSON does not. BSON seems &#x201C;blob-like&#x201D; but mongo speaks BSON and can &#x201C;reach in&#x201D; to documents. Powerful query language, with query optimizer. You can drop down to javascript also. Supports master/slave.
  2. Talk about harmony and how we are abusing mysql for key/value meta data on pages. Talk about capped collections and how they work like memcache. Also, how they are used for replication even.
  3. _id&#x2019;s can be any type, just have to be unique in collection
  4. find always returns a cursor that you can keep iterating through
  5. Don&#x2019;t have to typecast with mongo as it &#x201C;knows&#x201D; types but form submissions are always strings so typecasting has its benefits. * note required * note length * note numeric * note index
  6. multikey - automatically index arrays of object values ensure index on tags or _keywords