SlideShare une entreprise Scribd logo
1  sur  18
Télécharger pour lire hors ligne
MongoDB
Getting started, Couch, and MongoMapper
Who am I?
• Scott Motte / 25 / Perris, CA
• mid-level rubyist that prefers merb
• spitfiresky.com
• twitter.com/spitfiresky
• github.com/scottmotte
• scott@spitfiresky.com
Leopard Install (0.9.7)

•   mkdir -p /data/db 

•   wget http://downloads.mongodb.org/osx/mongodb-
    osx-i386-0.9.7.tgz 

•   sudo tar xvzf mongodb-osx-i386-0.9.7.tgz -C /usr/local

•   sudo cp -R /usr/local/mongodb-osx-i386-0.9.7/bin/ /usr/
    local/bin
Linux Install (0.9.7)
•   mkdir -p /data/db 

•   wget http://downloads.mongodb.org/linux/mongodb-
    linux-x86_64-0.9.6.tgz 

•   sudo tar -zxvf mongodb-linux-x86_64-0.9.7.tgz -C /usr/
    local

•   sudo chmod 755 -R /usr/local/mongodb-linux-
    x86_64-0.9.7 

•   sudo cp -R /usr/local/mongodb-linux-x86_64-0.9.7/bin/* /
    usr/local/bin
Running it

•   sudo mongod run & 

•   mongo (mysql-like command line)

     •   use bookstore_development

     •   db.books.save({ title: "Ender's Game", description:
         'zero gravity and mind games' })

     •   db.books.findOne()
Mongo or Couch
     Mongodb (C++)                    Couchdb (Erlang)
           drivers                             REST

 bson, document, schema-free        json, document, schema-free

  Dynamic queries, indexing                 map/reduce
             gridfs
                                            attachments
(needs an apache/nginx module)
            RAM                             http cache
  Good at the web, faster           Good at the web, slower
     development time                  development time
Update in place (good for high   MVCC (fault tolerant, but requires
        update rates)                     compacting)
        master-master                       replication

           50s kid                            indy kid
    *http://www.mongodb.org/display/DOCS/Comparing+Mongo+DB+and+Couch+DB
Mongodb orms
            Ruby                                                        Python
       mongo-ruby-driver                                 mongo-python-driver
     sudo gem install mongodb-mongo
                                                        easy_install pymongo (c extension auto-
  sudo gem install mongodb-mongo_ext (c
                                                                        installed)
                 extension)


    active-record-adapter                                              autumn
http://github.com/-mongodb/activerecord-mongo-adapter               http://autumn-orm.org/


            mongorecord                                        mongo-mapper
 http://github.com/mongodb/mongo-activerecord-ruby         http://github.com/jeffjenkins/mongo-mapper



           mongomapper
     http://github.com/jnunemaker/mongomapper
MongoMapper

sudo gem install mongomapper

config.gem 'jnunemaker-mongomapper' #rails

dependency 'jnunemaker-mongomapper' #merb
Model

class Book
  include MongoMapper::Document
  key :title, String
  key :description, String
end
Controller
class Books < Application
  def index
   @books = Book.all
   display @books
  end

 def show(id)
    @book = Book.find(id)
    raise NotFound unless @book
    display @book
 end
 ...
Validations
class Book
  include MongoMapper::Document
  key :title, String
  key :description, String

 validates_presence_of :title
 #validates_numericality_of
 #validates_length_of
 #validates_format_of
 #more
end



                           *http://github.com/jnunemaker/validatable
Callbacks
class Book
  ..
  key :description, String

 before_save :append_signature
 def append_signature
  self.description << " ~Corner Bookstore"
 end

 #after_save
 #before_validation
end


                 *http://api.rubyonrails.org/classes/ActiveSupport/Callbacks.html
Relationships
class Book
  include MongoMapper::Document
  key :title, String
  key :description, String
  has_many :reviews
end

class Review
  include MongoMapper::Document
  key :author, String
  key :review, String
  belongs_to :book
end
Relationships cont.
Finding
@book = Book.first
@reviews = @book.reviews

Displaying
@reviews.each do |review|
 review.author
end
@reviews[0] # return first review

Be careful
@user.tweets.size #slow
Tweet.count(:user_id => @user.id) #fast
Embedded Documents
class Review
  include MongoMapper::EmbeddedDocument

 key :uuid,    String, :default => XGen::Mongo::Driver::ObjectID.new
 key :author, String
 key :review, String
 key :created_at, Time, :default => Time.now.utc

 before_validation do
  self.uuid = XGen::Mongo::Driver::ObjectID.new
 end
end


*http://groups.google.com/group/mongomapper/browse_thread/thread/178b8c5105ebedd8
Embedded Docs cont.
class Reviews < Application
  ..
  def create(review)
     @flight = Flight.find(params['flight_id'])
     @review = Review.new(review)
     if @review.valid? && @flight.reviews << @review && @flight.save
       redirect '/wherever’' :message => {:notice => "Review made"}
     else
       message[:error] = "Review fail"
       render :new
     end
  end
end
# in router.rb
resources :flights, :identify => :id do
  resources :reviews, :identify => :uuid
end # /flights/:flight_id/comments/new
Additional info
• created_at and updated_at are included
  automatically by MongoMapper
• _id cannot currently be set with
  MongoMapper like it can in Couchrest
• cannot currently do @doc[‘custom_field’]
  like in couchrest.
• indexing: @doc.ensure_index :login
Conclusion
Mongodb is a great trade off
of speed, features, and
schema-less freedom, and it
now has its developer friendly
orm - mongomapper.

Strongly consider using it in a
web app you otherwise by
default would use mysql.

Then put together your
models and use script/server
or bin/merb -i to test your
performance improvements.

~ Scott Motte

Contenu connexe

Tendances

Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Justin Smestad
 
MongoDB Memory Management Demystified
MongoDB Memory Management DemystifiedMongoDB Memory Management Demystified
MongoDB Memory Management Demystified
MongoDB
 
MongoDB Shell Tips & Tricks
MongoDB Shell Tips & TricksMongoDB Shell Tips & Tricks
MongoDB Shell Tips & Tricks
MongoDB
 

Tendances (20)

Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
How do i Meet MongoDB
How do i Meet MongoDBHow do i Meet MongoDB
How do i Meet MongoDB
 
MongoDB Memory Management Demystified
MongoDB Memory Management DemystifiedMongoDB Memory Management Demystified
MongoDB Memory Management Demystified
 
MongoDB's New Aggregation framework
MongoDB's New Aggregation frameworkMongoDB's New Aggregation framework
MongoDB's New Aggregation framework
 
Mongo performance tuning: tips and tricks
Mongo performance tuning: tips and tricksMongo performance tuning: tips and tricks
Mongo performance tuning: tips and tricks
 
Back to Basics Spanish 4 Introduction to sharding
Back to Basics Spanish 4 Introduction to shardingBack to Basics Spanish 4 Introduction to sharding
Back to Basics Spanish 4 Introduction to sharding
 
Back to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDBBack to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDB
 
Mongo db workshop # 02
Mongo db workshop # 02Mongo db workshop # 02
Mongo db workshop # 02
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET Driver
 
MongoDB Shell Tips & Tricks
MongoDB Shell Tips & TricksMongoDB Shell Tips & Tricks
MongoDB Shell Tips & Tricks
 
MongoDB
MongoDBMongoDB
MongoDB
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
 
Connecting NodeJS & MongoDB
Connecting NodeJS & MongoDBConnecting NodeJS & MongoDB
Connecting NodeJS & MongoDB
 
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
MongoDB for Beginners
MongoDB for BeginnersMongoDB for Beginners
MongoDB for Beginners
 
MongoDB Days Silicon Valley: Winning the Dreamforce Hackathon with MongoDB
MongoDB Days Silicon Valley: Winning the Dreamforce Hackathon with MongoDBMongoDB Days Silicon Valley: Winning the Dreamforce Hackathon with MongoDB
MongoDB Days Silicon Valley: Winning the Dreamforce Hackathon with MongoDB
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 

Similaire à Mongodb

Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
MongoDB
 
MongoDB and Ruby on Rails
MongoDB and Ruby on RailsMongoDB and Ruby on Rails
MongoDB and Ruby on Rails
rfischer20
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
Marcelo Pinheiro
 

Similaire à Mongodb (20)

Rails with mongodb
Rails with mongodbRails with mongodb
Rails with mongodb
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
MongoDB and Node.js
MongoDB and Node.jsMongoDB and Node.js
MongoDB and Node.js
 
Introduction to using MongoDB with Ruby
Introduction to using MongoDB with RubyIntroduction to using MongoDB with Ruby
Introduction to using MongoDB with Ruby
 
[H3 2012] 우리가 모르는 Node.js로 할 수 있는 몇가지
[H3 2012] 우리가 모르는 Node.js로 할 수 있는 몇가지[H3 2012] 우리가 모르는 Node.js로 할 수 있는 몇가지
[H3 2012] 우리가 모르는 Node.js로 할 수 있는 몇가지
 
우리가 모르는 노드로 할 수 있는 몇가지
우리가 모르는 노드로 할 수 있는 몇가지우리가 모르는 노드로 할 수 있는 몇가지
우리가 모르는 노드로 할 수 있는 몇가지
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.js
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.js
 
Introduction to MongoDB with PHP
Introduction to MongoDB with PHPIntroduction to MongoDB with PHP
Introduction to MongoDB with PHP
 
Docker
DockerDocker
Docker
 
From Zero to Mongo, Art.sy Experience w/ MongoDB
From Zero to Mongo, Art.sy Experience w/ MongoDBFrom Zero to Mongo, Art.sy Experience w/ MongoDB
From Zero to Mongo, Art.sy Experience w/ MongoDB
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
MongoDB and Ruby on Rails
MongoDB and Ruby on RailsMongoDB and Ruby on Rails
MongoDB and Ruby on Rails
 
PHP Development Tools
PHP  Development ToolsPHP  Development Tools
PHP Development Tools
 
How to use MongoDB with CakePHP
How to use MongoDB with CakePHPHow to use MongoDB with CakePHP
How to use MongoDB with CakePHP
 
Build your first MongoDB App in Ruby @ StrangeLoop 2013
Build your first MongoDB App in Ruby @ StrangeLoop 2013Build your first MongoDB App in Ruby @ StrangeLoop 2013
Build your first MongoDB App in Ruby @ StrangeLoop 2013
 
Docker, c'est bonheur !
Docker, c'est bonheur !Docker, c'est bonheur !
Docker, c'est bonheur !
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
 

Dernier

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Dernier (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 

Mongodb

  • 2. Who am I? • Scott Motte / 25 / Perris, CA • mid-level rubyist that prefers merb • spitfiresky.com • twitter.com/spitfiresky • github.com/scottmotte • scott@spitfiresky.com
  • 3. Leopard Install (0.9.7) • mkdir -p /data/db • wget http://downloads.mongodb.org/osx/mongodb- osx-i386-0.9.7.tgz • sudo tar xvzf mongodb-osx-i386-0.9.7.tgz -C /usr/local • sudo cp -R /usr/local/mongodb-osx-i386-0.9.7/bin/ /usr/ local/bin
  • 4. Linux Install (0.9.7) • mkdir -p /data/db • wget http://downloads.mongodb.org/linux/mongodb- linux-x86_64-0.9.6.tgz • sudo tar -zxvf mongodb-linux-x86_64-0.9.7.tgz -C /usr/ local • sudo chmod 755 -R /usr/local/mongodb-linux- x86_64-0.9.7 • sudo cp -R /usr/local/mongodb-linux-x86_64-0.9.7/bin/* / usr/local/bin
  • 5. Running it • sudo mongod run & • mongo (mysql-like command line) • use bookstore_development • db.books.save({ title: "Ender's Game", description: 'zero gravity and mind games' }) • db.books.findOne()
  • 6. Mongo or Couch Mongodb (C++) Couchdb (Erlang) drivers REST bson, document, schema-free json, document, schema-free Dynamic queries, indexing map/reduce gridfs attachments (needs an apache/nginx module) RAM http cache Good at the web, faster Good at the web, slower development time development time Update in place (good for high MVCC (fault tolerant, but requires update rates) compacting) master-master replication 50s kid indy kid *http://www.mongodb.org/display/DOCS/Comparing+Mongo+DB+and+Couch+DB
  • 7. Mongodb orms Ruby Python mongo-ruby-driver mongo-python-driver sudo gem install mongodb-mongo easy_install pymongo (c extension auto- sudo gem install mongodb-mongo_ext (c installed) extension) active-record-adapter autumn http://github.com/-mongodb/activerecord-mongo-adapter http://autumn-orm.org/ mongorecord mongo-mapper http://github.com/mongodb/mongo-activerecord-ruby http://github.com/jeffjenkins/mongo-mapper mongomapper http://github.com/jnunemaker/mongomapper
  • 8. MongoMapper sudo gem install mongomapper config.gem 'jnunemaker-mongomapper' #rails dependency 'jnunemaker-mongomapper' #merb
  • 9. Model class Book include MongoMapper::Document key :title, String key :description, String end
  • 10. Controller class Books < Application def index @books = Book.all display @books end def show(id) @book = Book.find(id) raise NotFound unless @book display @book end ...
  • 11. Validations class Book include MongoMapper::Document key :title, String key :description, String validates_presence_of :title #validates_numericality_of #validates_length_of #validates_format_of #more end *http://github.com/jnunemaker/validatable
  • 12. Callbacks class Book .. key :description, String before_save :append_signature def append_signature self.description << " ~Corner Bookstore" end #after_save #before_validation end *http://api.rubyonrails.org/classes/ActiveSupport/Callbacks.html
  • 13. Relationships class Book include MongoMapper::Document key :title, String key :description, String has_many :reviews end class Review include MongoMapper::Document key :author, String key :review, String belongs_to :book end
  • 14. Relationships cont. Finding @book = Book.first @reviews = @book.reviews Displaying @reviews.each do |review| review.author end @reviews[0] # return first review Be careful @user.tweets.size #slow Tweet.count(:user_id => @user.id) #fast
  • 15. Embedded Documents class Review include MongoMapper::EmbeddedDocument key :uuid, String, :default => XGen::Mongo::Driver::ObjectID.new key :author, String key :review, String key :created_at, Time, :default => Time.now.utc before_validation do self.uuid = XGen::Mongo::Driver::ObjectID.new end end *http://groups.google.com/group/mongomapper/browse_thread/thread/178b8c5105ebedd8
  • 16. Embedded Docs cont. class Reviews < Application .. def create(review) @flight = Flight.find(params['flight_id']) @review = Review.new(review) if @review.valid? && @flight.reviews << @review && @flight.save redirect '/wherever’' :message => {:notice => "Review made"} else message[:error] = "Review fail" render :new end end end # in router.rb resources :flights, :identify => :id do resources :reviews, :identify => :uuid end # /flights/:flight_id/comments/new
  • 17. Additional info • created_at and updated_at are included automatically by MongoMapper • _id cannot currently be set with MongoMapper like it can in Couchrest • cannot currently do @doc[‘custom_field’] like in couchrest. • indexing: @doc.ensure_index :login
  • 18. Conclusion Mongodb is a great trade off of speed, features, and schema-less freedom, and it now has its developer friendly orm - mongomapper. Strongly consider using it in a web app you otherwise by default would use mysql. Then put together your models and use script/server or bin/merb -i to test your performance improvements. ~ Scott Motte