SlideShare una empresa de Scribd logo
1 de 30
Descargar para leer sin conexión
Using MongoDB with Ruby on Rails	
presented by Ryan Fischer, Founder of 20spokes
What is covered

• Why we use MongoDB and Ruby on Rails


• Choices made for Object Mapper


• Simple to get started!
Using MongoDB with Ruby on Rails

• Fast in-place updates with atomic modifiers


• Ruby on Rails is productive!


• Object Mappers available for MongoDB


• Mongo Ruby Driver
Mobile / Web

• Ruby on Rails makes REST easy, making APIs easier.


• Render responses as text, JSON, or XML


• Geospatial indexing for location based queries.


• Location-centric websites and mobile applications.
Why we chose MongoDB

• Cowrite - collaborative writing web application


   • Versioning needed


   • Originally using GridFS


• Travel720 - Gift registry web site


   • Self contained relations can take advantage of embedding documents
Mongo Object Mappers for Ruby	

• MongoMapper


• Mongoid


• Mongo ODM


• MongoModel
Why we chose Mongoid

• Excellent documentation


• Active community


• Compatibility with other projects/gems


• Similar API to ActiveRecord


• Uses ActiveValidation


• Mongoid Extras: Caching, Paranoid Documents, Versioning, Timestamping,
  Composite Keys
Compatible Gems with Mongoid	

• Devise - Authentication solution for Rails based on Warden. Supports
  Mongoid out of box.


• Carrierwave - simple and flexible way to upload files from Ruby Applications.
  Supports grid_fs.


• Geocoder - complete geocoding solution for Rails. Adds geocoding by street
  or IP address, reverse geocoding, and distance queries.


• Mongoid-rspec - RSpec matchers and macros for Mongoid.
Getting Started

Include in Gem file
 gem "mongoid", "~> 2.3"
 gem "bson_ext", "~> 1.4"


Run the install for Mongoid

 rails generate mongoid:config



That’s it!
mongoid.yml
development:
  host: localhost
  database: geekbusters_development

test:
  host: localhost
  database: geekbusters_test

production:
 host: <%= ENV['MONGOID_HOST'] %>
 port: <%= ENV['MONGOID_PORT'] %>
 username: <%= ENV['MONGOID_USERNAME'] %>
 password: <%= ENV['MONGOID_PASSWORD'] %>
 database: <%= ENV['MONGOID_DATABASE'] %>
  # slaves:
  #   - host: slave1.local
  #     port: 27018
  #   - host: slave2.local
  #     port: 27019
Developing with MongoDB/Mongoid

• Generating models is the same using the console as with ActiveRecord.


   • rails generate model Team name:string city:string
     location:array


• No migrations needed!


• Take advantage of embedded documents in models where applicable for
  increased performance.


• Store large files using GridFS
Fields available for Mongoid	

• Array                             • Range

• BigDecimal (Stored as a String)   • String

• Boolean                           • Symbol

• Date                              • Time

• DateTime

• Float

• Hash

• Integer
Mongoid Document

class Team
  include Mongoid::Document
  include Mongoid::Timestamps

  field :name, type: String
  field :city, type: String
  field :location, :type => Array

  validates :name, :city, :presence => true

end
Persisting in the Controller

def create
  Team.create(:city => "New York", :name => "Giants")
end


def update
  @team = Team.find(params[:id])
  @team = Team.update_attributes(params[:team])
end
Indexing
 class Team
   include Mongoid::Document

   field :name, type: String
   index :name, unique: true
 end

Indexing on multiple fields -

index(
  [
    [ :name, MONGO::ASCENDING ]
    [ :city, MONGO::ASCENDING ]
  ]
)
Indexing

To create indexes in the database use the rake task


   rake db:mongoid:create_indexes




Or configure to autocreate in mongoid.yml (not recommended)


    defaults: &defaults
      autocreate_indexes: true
Relations in Models

• Associations between models can be embedded or referenced


• NO JOINS!


• Objects that are referenced involve a separate query


• Embedded documents can be very efficient with reducing queries to one
  while managing the size of the document


• One to One, One to Many, and Many to Many relations available
Relations in Mongoid - Embedded

• Embedded Relations - stored inside other documents in the database.
 class Blog
   include Mongoid::Document
   embeds_many :posts
 end

 class Post
   include Mongoid::Document
   embedded_in :blog
 end
Embedded Posts


{ "_id" : ObjectId("4e9ba47fcdffba523f000004"),
  "name" : "Geekbusters Blog",
  "posts" :
  [
    {"content" : "Slimer is right behind you.",
      _id" : ObjectId("4e9ba47fcdffba523f000005")}
  ]
}
Polymorphic Behavior
class Image
  include Mongoid::Document
  embeds_many :comments, as: :commentable
end

class Document
  include Mongoid::Document
  embeds_many :comments, as: :commentable
end

class Comment
  include Mongoid::Document
  embedded_in :commentable, polymorphic: true
end
Relations in Mongoid - Referenced

Referenced Relations - stores reference to a document in another collection,
typically an id

class Blog
  include Mongoid::Document
  has_many :posts, dependent: :delete
end

class Post
  include Mongoid::Document
  belongs_to :blog
end
Many to Many Relationship

class Tag
  include Mongoid::Document
  has_and_belongs_to_many :posts
end

class Post
  include Mongoid::Document
  has_and_belongs_to_many :tags
end
Querying

• Queries are of type Criteria, which is a chainable and lazily evaluated wrapper
  to a MongoDB dynamic query.


• Chainable queries include:
    all_in         includes
    all_of         limit
    also_in        near
    and            not_in
    any_of         only
    asc            order_by
    desc           skip
    distinct       where
    excludes       without
Query Examples

Team.near(location: [20.70, 38.15]).limit(20)



Team.any_in(names: ["Giants", "Bears", "Lions"])



Team.find_or_create_by(name: "Giants")


Team.where(name: "Cowboys").destroy_all
Versioning with Mongoid	

• Embeds a version of the object on each save.


• Can skip versioning and also set the max versions.


• Add to model -



 include Mongoid::Versioning
Versioning Example
{"_id" : ObjectId("4e9ba7fdcdffba52d6000004"),
  "content" : "Impossible. I am too loud to fall asleep to.",
  "created_at" : ISODate("2011-10-17T03:58:53Z"),
  "title" : "Impossible to sleep to - this guy.",
  "updated_at" : ISODate("2011-10-17T03:58:53Z"),
  "version" : 3,
  "versions" : [
    {"title" : "Who is asleep?",
     "content" : "Wake up the guy next to you if they are asleep.
Thanks.",
     "version" : 1,
     "created_at" : ISODate("2011-10-17T03:58:53Z")},
    {"title" : "Who is asleep?",
     "content" : "Impossible. I am too loud to fall asleep to.",
     "created_at" : ISODate("2011-10-17T03:58:53Z"),
     "version" : 2 } ]
}
And More

• Identity Map


• Callbacks


• Scopes


• Dirty Tracking
Testing Rails with MongoDB

• RSpec-Mongoid provides test matchers


• RSpec does not refresh the database with each test run.


• Database Cleaner to the rescue. It be setup to truncate a database before
  running tests. Add below after installing the DatabaseCleaner Gem.

 config.before(:suite) do
   DatabaseCleaner.strategy = :truncation
   DatabaseCleaner.orm = "mongoid"
 end
Hosting Options

• Heroku is a widely used cloud hosting for Ruby on Rails


• MongoHQ and MongoLab both have add on options


• Options and pricing are similar
Thanks!!

Email: ryan.fischer@20spokes.com

Twitter: @ryanfischer20

Check out Geekbusters on Github

Más contenido relacionado

La actualidad más candente

AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)
AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)
AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)
Amazon Web Services Korea
 
AWS를 활용한 상품 추천 서비스 구축::김태현:: AWS Summit Seoul 2018
AWS를 활용한 상품 추천 서비스 구축::김태현:: AWS Summit Seoul 2018AWS를 활용한 상품 추천 서비스 구축::김태현:: AWS Summit Seoul 2018
AWS를 활용한 상품 추천 서비스 구축::김태현:: AWS Summit Seoul 2018
Amazon Web Services Korea
 
9월 웨비나 - AWS에서의 네트워크 보안 (이경수 솔루션즈 아키텍트)
9월 웨비나 - AWS에서의 네트워크 보안 (이경수 솔루션즈 아키텍트)9월 웨비나 - AWS에서의 네트워크 보안 (이경수 솔루션즈 아키텍트)
9월 웨비나 - AWS에서의 네트워크 보안 (이경수 솔루션즈 아키텍트)
Amazon Web Services Korea
 

La actualidad más candente (20)

글로벌 고객 사례를 통하여 소개하는 혁신적인 데이터 웨어하우스 - 김형일 (AWS 솔루션즈 아키텍트)
글로벌 고객 사례를 통하여 소개하는 혁신적인 데이터 웨어하우스 - 김형일 (AWS 솔루션즈 아키텍트)글로벌 고객 사례를 통하여 소개하는 혁신적인 데이터 웨어하우스 - 김형일 (AWS 솔루션즈 아키텍트)
글로벌 고객 사례를 통하여 소개하는 혁신적인 데이터 웨어하우스 - 김형일 (AWS 솔루션즈 아키텍트)
 
코리안리 - 데이터 분석 플랫폼 구축 여정, 그 시작과 과제 - 발표자: 김석기 그룹장, 데이터비즈니스센터, 메가존클라우드 ::: AWS ...
코리안리 - 데이터 분석 플랫폼 구축 여정, 그 시작과 과제 - 발표자: 김석기 그룹장, 데이터비즈니스센터, 메가존클라우드 ::: AWS ...코리안리 - 데이터 분석 플랫폼 구축 여정, 그 시작과 과제 - 발표자: 김석기 그룹장, 데이터비즈니스센터, 메가존클라우드 ::: AWS ...
코리안리 - 데이터 분석 플랫폼 구축 여정, 그 시작과 과제 - 발표자: 김석기 그룹장, 데이터비즈니스센터, 메가존클라우드 ::: AWS ...
 
Amazon Elasticache - Fully managed, Redis & Memcached Compatible Service (Lev...
Amazon Elasticache - Fully managed, Redis & Memcached Compatible Service (Lev...Amazon Elasticache - Fully managed, Redis & Memcached Compatible Service (Lev...
Amazon Elasticache - Fully managed, Redis & Memcached Compatible Service (Lev...
 
AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)
AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)
AWS CLOUD 2017 - AWS Shield를 통한 DDoS 대비 복원성 강한 AWS 보안 아키텍처 구성 (임기성 솔루션즈 아키텍트)
 
AWS Transit Gateway를 통한 Multi-VPC 아키텍처 패턴 - 강동환 솔루션즈 아키텍트, AWS :: AWS Summit ...
AWS Transit Gateway를 통한 Multi-VPC 아키텍처 패턴 - 강동환 솔루션즈 아키텍트, AWS :: AWS Summit ...AWS Transit Gateway를 통한 Multi-VPC 아키텍처 패턴 - 강동환 솔루션즈 아키텍트, AWS :: AWS Summit ...
AWS Transit Gateway를 통한 Multi-VPC 아키텍처 패턴 - 강동환 솔루션즈 아키텍트, AWS :: AWS Summit ...
 
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
 
Effective Data Lake : 고객 경험을 통한 사례 탐구 - 유다니엘 솔루션즈 아키텍트, AWS :: AWS Summit Seo...
Effective Data Lake : 고객 경험을 통한 사례 탐구 - 유다니엘 솔루션즈 아키텍트, AWS :: AWS Summit Seo...Effective Data Lake : 고객 경험을 통한 사례 탐구 - 유다니엘 솔루션즈 아키텍트, AWS :: AWS Summit Seo...
Effective Data Lake : 고객 경험을 통한 사례 탐구 - 유다니엘 솔루션즈 아키텍트, AWS :: AWS Summit Seo...
 
Migrating Microsoft SQL Server Databases to AWS – Best Practices and Patterns...
Migrating Microsoft SQL Server Databases to AWS – Best Practices and Patterns...Migrating Microsoft SQL Server Databases to AWS – Best Practices and Patterns...
Migrating Microsoft SQL Server Databases to AWS – Best Practices and Patterns...
 
AWS를 활용한 상품 추천 서비스 구축::김태현:: AWS Summit Seoul 2018
AWS를 활용한 상품 추천 서비스 구축::김태현:: AWS Summit Seoul 2018AWS를 활용한 상품 추천 서비스 구축::김태현:: AWS Summit Seoul 2018
AWS를 활용한 상품 추천 서비스 구축::김태현:: AWS Summit Seoul 2018
 
Amazon Dynamo DB 활용하기 - 강민석 :: AWS Database Modernization Day 온라인
Amazon Dynamo DB 활용하기 - 강민석 :: AWS Database Modernization Day 온라인Amazon Dynamo DB 활용하기 - 강민석 :: AWS Database Modernization Day 온라인
Amazon Dynamo DB 활용하기 - 강민석 :: AWS Database Modernization Day 온라인
 
[AWS Innovate 온라인 컨퍼런스] Amazon Personalize를 통한 개인화 추천 기능 실전 구현하기 - 최원근, AWS 솔...
[AWS Innovate 온라인 컨퍼런스] Amazon Personalize를 통한 개인화 추천 기능 실전 구현하기 - 최원근, AWS 솔...[AWS Innovate 온라인 컨퍼런스] Amazon Personalize를 통한 개인화 추천 기능 실전 구현하기 - 최원근, AWS 솔...
[AWS Innovate 온라인 컨퍼런스] Amazon Personalize를 통한 개인화 추천 기능 실전 구현하기 - 최원근, AWS 솔...
 
IDC 서버 몽땅 AWS로 이전하기 위한 5가지 방법 - 윤석찬 (AWS 테크에반젤리스트)
IDC 서버 몽땅 AWS로 이전하기 위한 5가지 방법 - 윤석찬 (AWS 테크에반젤리스트) IDC 서버 몽땅 AWS로 이전하기 위한 5가지 방법 - 윤석찬 (AWS 테크에반젤리스트)
IDC 서버 몽땅 AWS로 이전하기 위한 5가지 방법 - 윤석찬 (AWS 테크에반젤리스트)
 
게임 서비스를 위한 AWS상의 고성능 SQL 데이터베이스 구성 (이정훈 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
게임 서비스를 위한 AWS상의 고성능 SQL 데이터베이스 구성 (이정훈 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018게임 서비스를 위한 AWS상의 고성능 SQL 데이터베이스 구성 (이정훈 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
게임 서비스를 위한 AWS상의 고성능 SQL 데이터베이스 구성 (이정훈 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
 
Day 1 - Introduction to Cloud Computing with Amazon Web Services
Day 1 - Introduction to Cloud Computing with Amazon Web ServicesDay 1 - Introduction to Cloud Computing with Amazon Web Services
Day 1 - Introduction to Cloud Computing with Amazon Web Services
 
Getting Strated with Amazon Dynamo DB (Jim Scharf) - AWS DB Day
Getting Strated with Amazon Dynamo DB (Jim Scharf) - AWS DB DayGetting Strated with Amazon Dynamo DB (Jim Scharf) - AWS DB Day
Getting Strated with Amazon Dynamo DB (Jim Scharf) - AWS DB Day
 
데브옵스 엔지니어를 위한 신규 운영 서비스 - 김필중, AWS 개발 전문 솔루션즈 아키텍트 / 김현민, 메가존클라우드 솔루션즈 아키텍트 :...
데브옵스 엔지니어를 위한 신규 운영 서비스 - 김필중, AWS 개발 전문 솔루션즈 아키텍트 / 김현민, 메가존클라우드 솔루션즈 아키텍트 :...데브옵스 엔지니어를 위한 신규 운영 서비스 - 김필중, AWS 개발 전문 솔루션즈 아키텍트 / 김현민, 메가존클라우드 솔루션즈 아키텍트 :...
데브옵스 엔지니어를 위한 신규 운영 서비스 - 김필중, AWS 개발 전문 솔루션즈 아키텍트 / 김현민, 메가존클라우드 솔루션즈 아키텍트 :...
 
AWS Tutorial | AWS Certified Solutions Architect | Amazon AWS | AWS Training ...
AWS Tutorial | AWS Certified Solutions Architect | Amazon AWS | AWS Training ...AWS Tutorial | AWS Certified Solutions Architect | Amazon AWS | AWS Training ...
AWS Tutorial | AWS Certified Solutions Architect | Amazon AWS | AWS Training ...
 
AWS re:Invent 2016: Workshop: AWS S3 Deep-Dive Hands-On Workshop: Deploying a...
AWS re:Invent 2016: Workshop: AWS S3 Deep-Dive Hands-On Workshop: Deploying a...AWS re:Invent 2016: Workshop: AWS S3 Deep-Dive Hands-On Workshop: Deploying a...
AWS re:Invent 2016: Workshop: AWS S3 Deep-Dive Hands-On Workshop: Deploying a...
 
Kubernetes networking in AWS
Kubernetes networking in AWSKubernetes networking in AWS
Kubernetes networking in AWS
 
9월 웨비나 - AWS에서의 네트워크 보안 (이경수 솔루션즈 아키텍트)
9월 웨비나 - AWS에서의 네트워크 보안 (이경수 솔루션즈 아키텍트)9월 웨비나 - AWS에서의 네트워크 보안 (이경수 솔루션즈 아키텍트)
9월 웨비나 - AWS에서의 네트워크 보안 (이경수 솔루션즈 아키텍트)
 

Similar a MongoDB and Ruby on Rails

Mongodb at-gilt-groupe-seattle-2012-09-14-final
Mongodb at-gilt-groupe-seattle-2012-09-14-finalMongodb at-gilt-groupe-seattle-2012-09-14-final
Mongodb at-gilt-groupe-seattle-2012-09-14-final
MongoDB
 
Mongo db eveningschemadesign
Mongo db eveningschemadesignMongo db eveningschemadesign
Mongo db eveningschemadesign
MongoDB APAC
 
MongoDB at Gilt Groupe
MongoDB at Gilt GroupeMongoDB at Gilt Groupe
MongoDB at Gilt Groupe
MongoDB
 
Mongo db first steps with csharp
Mongo db first steps with csharpMongo db first steps with csharp
Mongo db first steps with csharp
Serdar Buyuktemiz
 
Mongo NYC PHP Development
Mongo NYC PHP Development Mongo NYC PHP Development
Mongo NYC PHP Development
Fitz Agard
 

Similar a MongoDB and Ruby on Rails (20)

Building your first app with MongoDB
Building your first app with MongoDBBuilding your first app with MongoDB
Building your first app with MongoDB
 
Mongodb at-gilt-groupe-seattle-2012-09-14-final
Mongodb at-gilt-groupe-seattle-2012-09-14-finalMongodb at-gilt-groupe-seattle-2012-09-14-final
Mongodb at-gilt-groupe-seattle-2012-09-14-final
 
Mongo db eveningschemadesign
Mongo db eveningschemadesignMongo db eveningschemadesign
Mongo db eveningschemadesign
 
MongoDB at Gilt Groupe
MongoDB at Gilt GroupeMongoDB at Gilt Groupe
MongoDB at Gilt Groupe
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
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
 
MongoDB Basics
MongoDB BasicsMongoDB Basics
MongoDB Basics
 
MongoDB Hadoop DC
MongoDB Hadoop DCMongoDB Hadoop DC
MongoDB Hadoop DC
 
MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB Introduction talk at Dr Dobbs Conference, MongoDB Evenings at Bangalo...
MongoDB Introduction talk at Dr Dobbs Conference, MongoDB Evenings at Bangalo...MongoDB Introduction talk at Dr Dobbs Conference, MongoDB Evenings at Bangalo...
MongoDB Introduction talk at Dr Dobbs Conference, MongoDB Evenings at Bangalo...
 
Mongo db first steps with csharp
Mongo db first steps with csharpMongo db first steps with csharp
Mongo db first steps with csharp
 
MongoDB World 2018: Tutorial - MongoDB & NodeJS: Zero to Hero in 80 Minutes
MongoDB World 2018: Tutorial - MongoDB & NodeJS: Zero to Hero in 80 MinutesMongoDB World 2018: Tutorial - MongoDB & NodeJS: Zero to Hero in 80 Minutes
MongoDB World 2018: Tutorial - MongoDB & NodeJS: Zero to Hero in 80 Minutes
 
MongoDB Pros and Cons
MongoDB Pros and ConsMongoDB Pros and Cons
MongoDB Pros and Cons
 
MongoDB
MongoDBMongoDB
MongoDB
 
MongoDB at ZPUGDC
MongoDB at ZPUGDCMongoDB at ZPUGDC
MongoDB at ZPUGDC
 
Building your first app with mongo db
Building your first app with mongo dbBuilding your first app with mongo db
Building your first app with mongo db
 
Mongo NYC PHP Development
Mongo NYC PHP Development Mongo NYC PHP Development
Mongo NYC PHP Development
 
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
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Using MongoDB For BigData in 20 Minutes
Using MongoDB For BigData in 20 MinutesUsing MongoDB For BigData in 20 Minutes
Using MongoDB For BigData in 20 Minutes
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
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
giselly40
 

Último (20)

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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
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...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 

MongoDB and Ruby on Rails

  • 1. Using MongoDB with Ruby on Rails presented by Ryan Fischer, Founder of 20spokes
  • 2. What is covered • Why we use MongoDB and Ruby on Rails • Choices made for Object Mapper • Simple to get started!
  • 3. Using MongoDB with Ruby on Rails • Fast in-place updates with atomic modifiers • Ruby on Rails is productive! • Object Mappers available for MongoDB • Mongo Ruby Driver
  • 4. Mobile / Web • Ruby on Rails makes REST easy, making APIs easier. • Render responses as text, JSON, or XML • Geospatial indexing for location based queries. • Location-centric websites and mobile applications.
  • 5. Why we chose MongoDB • Cowrite - collaborative writing web application • Versioning needed • Originally using GridFS • Travel720 - Gift registry web site • Self contained relations can take advantage of embedding documents
  • 6. Mongo Object Mappers for Ruby • MongoMapper • Mongoid • Mongo ODM • MongoModel
  • 7. Why we chose Mongoid • Excellent documentation • Active community • Compatibility with other projects/gems • Similar API to ActiveRecord • Uses ActiveValidation • Mongoid Extras: Caching, Paranoid Documents, Versioning, Timestamping, Composite Keys
  • 8. Compatible Gems with Mongoid • Devise - Authentication solution for Rails based on Warden. Supports Mongoid out of box. • Carrierwave - simple and flexible way to upload files from Ruby Applications. Supports grid_fs. • Geocoder - complete geocoding solution for Rails. Adds geocoding by street or IP address, reverse geocoding, and distance queries. • Mongoid-rspec - RSpec matchers and macros for Mongoid.
  • 9. Getting Started Include in Gem file gem "mongoid", "~> 2.3" gem "bson_ext", "~> 1.4" Run the install for Mongoid rails generate mongoid:config That’s it!
  • 10. mongoid.yml development: host: localhost database: geekbusters_development test: host: localhost database: geekbusters_test production: host: <%= ENV['MONGOID_HOST'] %> port: <%= ENV['MONGOID_PORT'] %> username: <%= ENV['MONGOID_USERNAME'] %> password: <%= ENV['MONGOID_PASSWORD'] %> database: <%= ENV['MONGOID_DATABASE'] %> # slaves: # - host: slave1.local # port: 27018 # - host: slave2.local # port: 27019
  • 11. Developing with MongoDB/Mongoid • Generating models is the same using the console as with ActiveRecord. • rails generate model Team name:string city:string location:array • No migrations needed! • Take advantage of embedded documents in models where applicable for increased performance. • Store large files using GridFS
  • 12. Fields available for Mongoid • Array • Range • BigDecimal (Stored as a String) • String • Boolean • Symbol • Date • Time • DateTime • Float • Hash • Integer
  • 13. Mongoid Document class Team include Mongoid::Document include Mongoid::Timestamps field :name, type: String field :city, type: String field :location, :type => Array validates :name, :city, :presence => true end
  • 14. Persisting in the Controller def create Team.create(:city => "New York", :name => "Giants") end def update @team = Team.find(params[:id]) @team = Team.update_attributes(params[:team]) end
  • 15. Indexing class Team include Mongoid::Document field :name, type: String index :name, unique: true end Indexing on multiple fields - index( [ [ :name, MONGO::ASCENDING ] [ :city, MONGO::ASCENDING ] ] )
  • 16. Indexing To create indexes in the database use the rake task rake db:mongoid:create_indexes Or configure to autocreate in mongoid.yml (not recommended) defaults: &defaults autocreate_indexes: true
  • 17. Relations in Models • Associations between models can be embedded or referenced • NO JOINS! • Objects that are referenced involve a separate query • Embedded documents can be very efficient with reducing queries to one while managing the size of the document • One to One, One to Many, and Many to Many relations available
  • 18. Relations in Mongoid - Embedded • Embedded Relations - stored inside other documents in the database. class Blog include Mongoid::Document embeds_many :posts end class Post include Mongoid::Document embedded_in :blog end
  • 19. Embedded Posts { "_id" : ObjectId("4e9ba47fcdffba523f000004"), "name" : "Geekbusters Blog", "posts" : [ {"content" : "Slimer is right behind you.", _id" : ObjectId("4e9ba47fcdffba523f000005")} ] }
  • 20. Polymorphic Behavior class Image include Mongoid::Document embeds_many :comments, as: :commentable end class Document include Mongoid::Document embeds_many :comments, as: :commentable end class Comment include Mongoid::Document embedded_in :commentable, polymorphic: true end
  • 21. Relations in Mongoid - Referenced Referenced Relations - stores reference to a document in another collection, typically an id class Blog include Mongoid::Document has_many :posts, dependent: :delete end class Post include Mongoid::Document belongs_to :blog end
  • 22. Many to Many Relationship class Tag include Mongoid::Document has_and_belongs_to_many :posts end class Post include Mongoid::Document has_and_belongs_to_many :tags end
  • 23. Querying • Queries are of type Criteria, which is a chainable and lazily evaluated wrapper to a MongoDB dynamic query. • Chainable queries include: all_in includes all_of limit also_in near and not_in any_of only asc order_by desc skip distinct where excludes without
  • 24. Query Examples Team.near(location: [20.70, 38.15]).limit(20) Team.any_in(names: ["Giants", "Bears", "Lions"]) Team.find_or_create_by(name: "Giants") Team.where(name: "Cowboys").destroy_all
  • 25. Versioning with Mongoid • Embeds a version of the object on each save. • Can skip versioning and also set the max versions. • Add to model - include Mongoid::Versioning
  • 26. Versioning Example {"_id" : ObjectId("4e9ba7fdcdffba52d6000004"), "content" : "Impossible. I am too loud to fall asleep to.", "created_at" : ISODate("2011-10-17T03:58:53Z"), "title" : "Impossible to sleep to - this guy.", "updated_at" : ISODate("2011-10-17T03:58:53Z"), "version" : 3, "versions" : [ {"title" : "Who is asleep?", "content" : "Wake up the guy next to you if they are asleep. Thanks.", "version" : 1, "created_at" : ISODate("2011-10-17T03:58:53Z")}, {"title" : "Who is asleep?", "content" : "Impossible. I am too loud to fall asleep to.", "created_at" : ISODate("2011-10-17T03:58:53Z"), "version" : 2 } ] }
  • 27. And More • Identity Map • Callbacks • Scopes • Dirty Tracking
  • 28. Testing Rails with MongoDB • RSpec-Mongoid provides test matchers • RSpec does not refresh the database with each test run. • Database Cleaner to the rescue. It be setup to truncate a database before running tests. Add below after installing the DatabaseCleaner Gem. config.before(:suite) do DatabaseCleaner.strategy = :truncation DatabaseCleaner.orm = "mongoid" end
  • 29. Hosting Options • Heroku is a widely used cloud hosting for Ruby on Rails • MongoHQ and MongoLab both have add on options • Options and pricing are similar