SlideShare a Scribd company logo
Stash the Hash!

MongoDB is the MashupDB
      Mongo Austin   February 15, 2011




                                         WYNNNETHERLAND
whoami
+
MongoDB is the MashupDB
Two years ago...
MongoDB is the MashupDB
x
    No SQL?


       x
MongoDB
          x
Let's just skip to here already!



x
One year ago
CTO of Amazon




NoSQL   Smackdown!
Today
is it web scale?
x
How do we get to here?
       x
x
Enlightenment
Almost
  ^
    Two years with
Our journey
TweetCongress.org
“We the Tweeple of the United
States, in order to form a more
perfect government, establish
communication, and promote
transparency do hereby tweet the
Congress of the United States of
America.”
and aggregator
                           ^
The idea: A Twitter directory for the US Congress
MongoDB is the MashupDB
When does NOSQL make sense?
★ 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/
Key value stores
 Project Voldemort

                           me ver  y cool
 Ringo
 Scalaris
                        So                space
 Kai
                           ojects in this
 Dynomite
 MemcacheDB
                        pr
 ThruDB
 CouchDB
 Cassandra
 HBase
 Hypertable
 Redis
 Tokyo Cabinet/Tyrant
 Riak
 Neo4J
Tokyo Cabinet
MongoDB is the MashupDB
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/
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
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.
               Duplication reduced.
                                               TheDenormalized. Docs usually selfdetails
                                                   devil'soften duplicated.contained. Data
                                                                 in the

     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
http://damienkatz.net/files/What is CouchDB.pdf
why I
Mongo speaks JSON
Document Storage (BSON)                     B is for Binary

        { 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' }
            ]
        }


     Sure wish JSON did this...


http://www.mongodb.org/display/DOCS/BSON
That looks like JSON
versatility
MongoDB is the MashupDB
Runs like Hayes.
Hits like Mays.
Introducing
★ Built For Speedcan be very fast

★ Dynamic Queries and Indexes
★ Replication and Failover
★ Sharding
★ Map / Reduce
★ Geospatial stuffs
MongoDB is great for
 ★ Websites
                         Your own queryable API mirror
 ★ Caching
 ★ High volume, low value
 ★ High scalability                          stash the hash

 ★ Storage of program objects and JSON
Not as great for
 ★ Highly transactional
 ★ Financial stuffs
 ★ 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

                                     Ruby driver for MongoDB

 ★ gem install mongo
                                           Native C
 ★ gem install mongo_ext                   extensions ( go turbo! )


 ★ gem install mongo_mapper
brew install mongodb
Contents of mongo/bin                 what's in the box?



 ★ mongod - The MongoDB server
 ★ mongo - the JavaScript interactive shell
 ★ mongoexport - export data as JSON or csv
 ★ mongoimport - As advertised
                                                                was?
 ★ mongodump - Like mysqldump        why? What did you think it


 ★ mongorestore - Restore from mongodump les
 ★ mongos - Auto-sharding module (getting better with every build)
Some new terms
When I say   think

 database     database
              Well that one isn't new...
Databases in MongoDB
 ★ Made up of multiple collections
 ★ Are created on-the- y when rst referenced
When I say    think

 collection    table
Collections in MongoDB
 ★ Schema-less    but typed!


 ★ For grouping documents into smaller query sets (speed)
 ★ Indexable by one or more key
 ★ Are created on-the- y when rst referenced
 ★ Capped collections: Fixed size, older records dropped after limit
   reached
When I say   think

 document     record or row
The Ruby ecosystem
The Ruby driver
Querying
db.collection.find({'first_name': 'John'}) # finds all Johns

db.collection.find({'first_name': /^wynn/i}) # regex

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

db.collection.find({'age': {'$gte': 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)

  db.collection.mapReduce(mapfunction,reducefunction[,options]);
Updating
$inc, $set, $unset, $push, $pushAll, $addToSet,
$pop, $pull, $pullAll, $rename, $bit
MongoDB is the MashupDB
akfast w it h
B re
      Nune maker
John
MongoMapper           from @jnunemaker

 ★ Mongo is not MySQL
 ★ DSL for modeling domain should also teach you Mongo
 ★ Now in version 0.8.6




  I voted for "Nunemapper"
Features
★ Typecasting
★ Callbacks (ActiveSupport Callbacks)
★ Validations
★ Connection and database can differ per document
★ Create and Update with single or multiple
★ Delete and Destroy and _all counterparts
                                         Be careful. Ordering can be tricky.
★ Find: id, ids, :all, : rst, :last
★ Associations
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
                             Included as module, not subclassed
class Address
  include MongoMapper::Document
  key :street, String
  key :city, String
  key :state, String, :length => 2
  key :zip, Integer, :numeric => true, :length => 5
end
Queries
User.where(:age.gt   =>   27).sort(:age).all
User.where(:age.gt   =>   27).sort(:age.desc).all
User.where(:age.gt   =>   27).sort(:age).limit(1).all
User.where(:age.gt   =>   27).sort(:age).skip(1).limit(1).all
Scopes
class User
  include MongoMapper::Document

  # plain old vanilla scopes with fancy queries
  scope :johns,   where(:name => 'John')

  # plain old vanilla scopes with hashes
  scope :bills, :name => 'Bill'

  # dynamic scopes with parameters
  scope :by_name, lambda { |name| where(:name => name) }
  scope :by_ages, lambda { |low, high| where(:age.gte => low, :age.lte => high) }

  # Yep, even plain old methods work as long as they return a query
  def self.by_tag(tag)
    where(:tags => tag)
  end

  # You can even make a method that returns a scope
  def self.twenties; by_ages(20, 29) end

  key :name, String
  key :tags, Array
end
Scopes
# simple scopes
pp User.johns.first
pp User.bills.first

# scope with arg
pp User.by_name('Frank').first

# scope with two args
pp User.by_ages(20, 29).all

# chaining class methods on scopes
pp User.by_ages(20, 40).by_tag('ruby').all

# scope made using method that returns scope
pp User.twenties.all
Mongoid
Mongomatic
Mongomatic
require 'mongomatic'
 
class User < Mongomatic::Base
  def validate
    self.errors.add "name", "can't be empty" if self["name"].blank?
    self.errors.add "email", "can't be empty" if self["email"].blank?
  end
end
 
# set the db for all models:
Mongomatic.db = Mongo::Connection.new.db("mongomatic_test")
# or you can set it for a specific model:
User.db = Mongo::Connection.new.db("mongomatic_test_user")
 
Mongomatic
User.empty?
=> true
u = User.new(:name => "Ben")
=> #<user:0x00000100d0cbf8 @doc="{"name"=">"Ben"}, @removed=false>
u.valid?
=> false
u["email"] = "me@somewhere.com"
u.valid?
=> true
u.insert
=> BSON::ObjectId('4c32834f0218236321000001')
 
User.empty?
=> false
MongoDB is open source
Mongo runs in the cloud
#mongodb
How can you help?
 ★ We need an awesome admin GUI
 ★ Port some plugins (might get easier with ActiveModel support
   coming soon)
 ★ Build something cool
Lessons learned in production                      the fine print

 ★ The laws of computing are still in effect            Upserts FTW!
 ★ Indexes are important no matter what the salesman told ya about
   performance
 ★ Data modeling. Deep or Wide?     The answer is yes!


 ★ MongoDB and MongoMapper are in active development
                  Very responsive yet very volatile changes!
10gen
Get the backstory on
Questions?

    wynn@hp.com
     @pengwynn

More Related Content

PDF
Hands on with Ruby & MongoDB
KEY
MongoDB - Ruby document store that doesn't rhyme with ouch
PPT
Mongo-Drupal
PDF
Wordcamp Fayetteville Pods Presentation (PDF)
ODP
HTML5, CSS, JavaScript Style guide and coding conventions
PDF
ODP
DrupalCon Chicago Practical MongoDB and Drupal
PPTX
Simple introduction Sass
Hands on with Ruby & MongoDB
MongoDB - Ruby document store that doesn't rhyme with ouch
Mongo-Drupal
Wordcamp Fayetteville Pods Presentation (PDF)
HTML5, CSS, JavaScript Style guide and coding conventions
DrupalCon Chicago Practical MongoDB and Drupal
Simple introduction Sass

What's hot (20)

PDF
Developing CouchApps
PDF
Preprocessor presentation
PDF
CSS 開發加速指南-Sass & Compass
KEY
The Cascade, Grids, Headings, and Selectors from an OOCSS Perspective, Ajax ...
ODP
Introducing Modern Perl
PPTX
Code for Startup MVP (Ruby on Rails) Session 2
PPT
CSS Preprocessors: LESS is more or look SASS-y trying
PDF
Build your first MongoDB App in Ruby @ StrangeLoop 2013
PDF
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
PPT
Allura - an Open Source MongoDB Based Document Oriented SourceForge
PDF
Apache AVRO (Boston HUG, Jan 19, 2010)
PDF
It's 2017, and I still want to sell you a graph database
PPT
An Introduction to CSS Preprocessors (SASS & LESS)
PPTX
Write LESS. DO more.
PPTX
SASS is more than LESS
ODP
Sass presentation
PDF
MongoDB, Hadoop and humongous data - MongoSV 2012
KEY
Object Relational Mapping in PHP
PDF
WordPress Café: Using WordPress as a Framework
PPTX
Doing More With Less
Developing CouchApps
Preprocessor presentation
CSS 開發加速指南-Sass & Compass
The Cascade, Grids, Headings, and Selectors from an OOCSS Perspective, Ajax ...
Introducing Modern Perl
Code for Startup MVP (Ruby on Rails) Session 2
CSS Preprocessors: LESS is more or look SASS-y trying
Build your first MongoDB App in Ruby @ StrangeLoop 2013
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
Allura - an Open Source MongoDB Based Document Oriented SourceForge
Apache AVRO (Boston HUG, Jan 19, 2010)
It's 2017, and I still want to sell you a graph database
An Introduction to CSS Preprocessors (SASS & LESS)
Write LESS. DO more.
SASS is more than LESS
Sass presentation
MongoDB, Hadoop and humongous data - MongoSV 2012
Object Relational Mapping in PHP
WordPress Café: Using WordPress as a Framework
Doing More With Less
Ad

Viewers also liked (10)

PDF
GraphDay Stockholm - Fraud Prevention
PDF
Fraud detection, whiplash for cash scheme and Neo4j
PPTX
Mongo DB in gaming industry
DOCX
Bank Failures and Case Studies
PDF
Dex: Introduction
PDF
How to apply graph analytics for bank loan fraud detection?
PPTX
Fraud principles1
PPTX
Fraud in the Banking Sector
PDF
Intro to Neo4j and Graph Databases
PPT
Presentation on fraud prevention, detection & control
GraphDay Stockholm - Fraud Prevention
Fraud detection, whiplash for cash scheme and Neo4j
Mongo DB in gaming industry
Bank Failures and Case Studies
Dex: Introduction
How to apply graph analytics for bank loan fraud detection?
Fraud principles1
Fraud in the Banking Sector
Intro to Neo4j and Graph Databases
Presentation on fraud prevention, detection & control
Ad

Similar to MongoDB is the MashupDB (20)

KEY
DynamoDB Gluecon 2012
ZIP
Gluecon 2012 - DynamoDB
PDF
Spring one2gx2010 spring-nonrelational_data
PPTX
KEY
NoSQL: Why, When, and How
PDF
Non Relational Databases
PPTX
JS App Architecture
KEY
PPTX
mongodb11 (1) (1).pptx
PPT
Mongo Bb - NoSQL tutorial
PDF
No sq lv1_0
PPTX
NoSQL
PPTX
Mongodb - NoSql Database
PPTX
Mongo db
PPTX
Introduction to mongoose and mongodband others
PPTX
Navigating NoSQL in cloudy skies
PPTX
Introduction to NoSql
PPTX
No SQL : Which way to go? Presented at DDDMelbourne 2015
PPTX
NoSQL, which way to go?
PDF
MongoDB at FrozenRails
DynamoDB Gluecon 2012
Gluecon 2012 - DynamoDB
Spring one2gx2010 spring-nonrelational_data
NoSQL: Why, When, and How
Non Relational Databases
JS App Architecture
mongodb11 (1) (1).pptx
Mongo Bb - NoSQL tutorial
No sq lv1_0
NoSQL
Mongodb - NoSql Database
Mongo db
Introduction to mongoose and mongodband others
Navigating NoSQL in cloudy skies
Introduction to NoSql
No SQL : Which way to go? Presented at DDDMelbourne 2015
NoSQL, which way to go?
MongoDB at FrozenRails

More from Wynn Netherland (11)

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

Recently uploaded (20)

PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
cuic standard and advanced reporting.pdf
PPT
Teaching material agriculture food technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Electronic commerce courselecture one. Pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Approach and Philosophy of On baking technology
PDF
Empathic Computing: Creating Shared Understanding
Chapter 3 Spatial Domain Image Processing.pdf
20250228 LYD VKU AI Blended-Learning.pptx
cuic standard and advanced reporting.pdf
Teaching material agriculture food technology
The Rise and Fall of 3GPP – Time for a Sabbatical?
Electronic commerce courselecture one. Pdf
Spectral efficient network and resource selection model in 5G networks
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
NewMind AI Monthly Chronicles - July 2025
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Advanced methodologies resolving dimensionality complications for autism neur...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Per capita expenditure prediction using model stacking based on satellite ima...
Digital-Transformation-Roadmap-for-Companies.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
NewMind AI Weekly Chronicles - August'25 Week I
Approach and Philosophy of On baking technology
Empathic Computing: Creating Shared Understanding

MongoDB is the MashupDB

  • 1. Stash the Hash! MongoDB is the MashupDB Mongo Austin February 15, 2011 WYNNNETHERLAND
  • 3. +
  • 7. x No SQL? x
  • 9. Let's just skip to here already! x
  • 11. CTO of Amazon NoSQL Smackdown!
  • 12. Today
  • 13. is it web scale?
  • 14. x
  • 15. How do we get to here? x x
  • 17. Almost ^ Two years with
  • 20. “We the Tweeple of the United States, in order to form a more perfect government, establish communication, and promote transparency do hereby tweet the Congress of the United States of America.”
  • 21. and aggregator ^ The idea: A Twitter directory for the US Congress
  • 23. When does NOSQL make sense? ★ 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/
  • 24. Key value stores Project Voldemort me ver y cool Ringo Scalaris So space Kai ojects in this Dynomite MemcacheDB pr ThruDB CouchDB Cassandra HBase Hypertable Redis Tokyo Cabinet/Tyrant Riak Neo4J
  • 27. 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/
  • 28. 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 http://damienkatz.net/files/What is CouchDB.pdf
  • 29. 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. Duplication reduced. TheDenormalized. Docs usually selfdetails devil'soften duplicated.contained. Data in the 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 http://damienkatz.net/files/What is CouchDB.pdf
  • 30. why I
  • 32. Document Storage (BSON) B is for Binary { 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' } ] } Sure wish JSON did this... http://www.mongodb.org/display/DOCS/BSON
  • 36. Runs like Hayes. Hits like Mays.
  • 37. Introducing ★ Built For Speedcan be very fast ★ Dynamic Queries and Indexes ★ Replication and Failover ★ Sharding ★ Map / Reduce ★ Geospatial stuffs
  • 38. MongoDB is great for ★ Websites Your own queryable API mirror ★ Caching ★ High volume, low value ★ High scalability stash the hash ★ Storage of program objects and JSON
  • 39. Not as great for ★ Highly transactional ★ Financial stuffs ★ Problems requiring SQL
  • 40. Installation ★ mkdir -p /data/db ★ download pre-built for OSX and unzip to /usr/local/ ★ cp -R /usr/local/pathtomongo/bin /usr/local/bin Ruby driver for MongoDB ★ gem install mongo Native C ★ gem install mongo_ext extensions ( go turbo! ) ★ gem install mongo_mapper
  • 42. Contents of mongo/bin what's in the box? ★ mongod - The MongoDB server ★ mongo - the JavaScript interactive shell ★ mongoexport - export data as JSON or csv ★ mongoimport - As advertised was? ★ mongodump - Like mysqldump why? What did you think it ★ mongorestore - Restore from mongodump les ★ mongos - Auto-sharding module (getting better with every build)
  • 44. When I say think database database Well that one isn't new...
  • 45. Databases in MongoDB ★ Made up of multiple collections ★ Are created on-the- y when rst referenced
  • 46. When I say think collection table
  • 47. Collections in MongoDB ★ Schema-less but typed! ★ For grouping documents into smaller query sets (speed) ★ Indexable by one or more key ★ Are created on-the- y when rst referenced ★ Capped collections: Fixed size, older records dropped after limit reached
  • 48. When I say think document record or row
  • 51. Querying db.collection.find({'first_name': 'John'}) # finds all Johns db.collection.find({'first_name': /^wynn/i}) # regex db.collection.find_first({'_id':1}) # finds first with _id of 1 db.collection.find({'age': {'$gte': 21}}) # finds possible drinkers db.collection.find({'author.first_name':'John'}) # subdocument db.collection.find({$where:'this.age >= 6 && this.age <= 18'})
  • 52. 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) db.collection.mapReduce(mapfunction,reducefunction[,options]);
  • 53. Updating $inc, $set, $unset, $push, $pushAll, $addToSet, $pop, $pull, $pullAll, $rename, $bit
  • 55. akfast w it h B re Nune maker John
  • 56. MongoMapper from @jnunemaker ★ Mongo is not MySQL ★ DSL for modeling domain should also teach you Mongo ★ Now in version 0.8.6 I voted for "Nunemapper"
  • 57. Features ★ Typecasting ★ Callbacks (ActiveSupport Callbacks) ★ Validations ★ Connection and database can differ per document ★ Create and Update with single or multiple ★ Delete and Destroy and _all counterparts Be careful. Ordering can be tricky. ★ Find: id, ids, :all, : rst, :last ★ Associations
  • 58. 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 Included as module, not subclassed class Address include MongoMapper::Document key :street, String key :city, String key :state, String, :length => 2 key :zip, Integer, :numeric => true, :length => 5 end
  • 59. Queries User.where(:age.gt => 27).sort(:age).all User.where(:age.gt => 27).sort(:age.desc).all User.where(:age.gt => 27).sort(:age).limit(1).all User.where(:age.gt => 27).sort(:age).skip(1).limit(1).all
  • 60. Scopes class User include MongoMapper::Document # plain old vanilla scopes with fancy queries scope :johns, where(:name => 'John') # plain old vanilla scopes with hashes scope :bills, :name => 'Bill' # dynamic scopes with parameters scope :by_name, lambda { |name| where(:name => name) } scope :by_ages, lambda { |low, high| where(:age.gte => low, :age.lte => high) } # Yep, even plain old methods work as long as they return a query def self.by_tag(tag) where(:tags => tag) end # You can even make a method that returns a scope def self.twenties; by_ages(20, 29) end key :name, String key :tags, Array end
  • 61. Scopes # simple scopes pp User.johns.first pp User.bills.first # scope with arg pp User.by_name('Frank').first # scope with two args pp User.by_ages(20, 29).all # chaining class methods on scopes pp User.by_ages(20, 40).by_tag('ruby').all # scope made using method that returns scope pp User.twenties.all
  • 64. Mongomatic require 'mongomatic'   class User < Mongomatic::Base   def validate     self.errors.add "name", "can't be empty" if self["name"].blank?     self.errors.add "email", "can't be empty" if self["email"].blank?   end end   # set the db for all models: Mongomatic.db = Mongo::Connection.new.db("mongomatic_test") # or you can set it for a specific model: User.db = Mongo::Connection.new.db("mongomatic_test_user")  
  • 65. Mongomatic User.empty? => true u = User.new(:name => "Ben") => #<user:0x00000100d0cbf8 @doc="{"name"=">"Ben"}, @removed=false> u.valid? => false u["email"] = "me@somewhere.com" u.valid? => true u.insert => BSON::ObjectId('4c32834f0218236321000001')   User.empty? => false
  • 66. MongoDB is open source
  • 67. Mongo runs in the cloud
  • 69. How can you help? ★ We need an awesome admin GUI ★ Port some plugins (might get easier with ActiveModel support coming soon) ★ Build something cool
  • 70. Lessons learned in production the fine print ★ The laws of computing are still in effect Upserts FTW! ★ Indexes are important no matter what the salesman told ya about performance ★ Data modeling. Deep or Wide? The answer is yes! ★ MongoDB and MongoMapper are in active development Very responsive yet very volatile changes!
  • 71. 10gen
  • 73. Questions? wynn@hp.com @pengwynn