public
Created — forked from banker/basics.rb

Files used in a presentation on MongoDB and Ruby

  • Download Gist
basics.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
require 'rubygems'
require 'mongo'
 
@con = Mongo::Connection.new
 
# Instance of Mongo::DB
@db = @con['webinar']
 
# Instance of Mongo::Collection
@col = @db['users']
 
@doc = { :first => "Kyle",
:last => "Banker",
:city => "NYC",
:loc => [40.1, -73],
:status => 0
}
 
id = @col.insert(@doc)
 
@col.update({'_id' => id})
 
 
puts "\nCursors and queries"
# Instance of Mongo::Cursor
@cursor = @col.find
 
# Implements Enumerable
@cursor.each do |doc|
p doc
end
 
# Manual iteration
@cursor = @col.find
while @cursor.has_next?
p @cursor.next_document
end
 
# Collection#find_one doesn't create a cursor
p @col.find_one
 
puts "\nRunning a command"
# BSON::OrderedHash (not needed in 1.9)
# Sometimes documents need ordering, as when running commands
# The command key must come first
@cmd = BSON::OrderedHash.new
@cmd['findAndModify'] = 'users'
@cmd['query'] = {:first => "Kyle"}
@cmd['update'] = {:$set => {:status => 2}}
 
p @db.command(@cmd)
 
@col.remove
 
# Executables
# - j2bson
# - b2json
# - mongo_console
connect.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
require 'rubygems'
require 'logger'
require 'mongo'
 
# Connecting to a single mongod or to mongos
# 'localhost', 27017
Mongo::Connection.new
 
# Host / port parameters
Mongo::Connection.new('localhost', 27017)
 
# With logging
# Note: this make things slower. Not for high performance apps.
@logger = Logger.new('mongo-ruby.log')
@con = Mongo::Connection.new('localhost', 27017, :logger => @logger)
@con['test']['foo'].save({:foo => "bar"})
 
# Connection to a secondary or slave node
Mongo::Connection.new('localhost', 27017, :slave_ok => true)
 
# Using Mongo URI
Mongo::Connection.from_uri("mongo://localhost:27017")
jruby.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11
require 'rubygems'
require 'mongo'
 
p BSON::BSON_CODER
 
# Since you can build true, multi-threaded apps, connection pooling
# will be most useful here.
# pool_size = number of threads, where one thread is allocated per connection.
# timeout is the amount of time to wait for a new connection before raising an exception
# This works for ReplSetConnection too.
Mongo::Connection.new('localhost', 27017, :pool_size => 10, :timeout => 500)
om.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Object mappers
 
 
# MongoDoc
# MongoMatic
# Candy
# MongoMapper
# Mongoid
 
 
# I recommend MongoMapper. However, lots of works has gone into
# the other projects. You should decide based on tests, review of the
# code base, successful projects.
 
# Common feautures
# - Validation
# - Associations (Document-document, Embedded, and Polymorphic)
om_rules_of_thumb.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Rules of thumb
 
# 1. Know your tools.
# - MongoDB
# - Driver
# - Object Mapper (Read the code!)
 
 
# 2. Don't let abstractions make you weak or lead you astray.
# - Documents should be no more than a couple levels deep.
# - And generally no larger than 100KB.
# - Going against either of the above is a code smell.
 
 
# 3. Don't declare indexes in your model.
# - An index is a migration and therefore should not be built automatically.
# - Mongoid has a rake task for build indexes.
repl_set_connect.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
require 'rubygems'
require 'mongo'
 
# Note: this assumes a replica set with three nodes on
# localhost, starting at 30000
 
# Basic connection
# Note: it's best to specify all seed node in your app
Mongo::ReplSetConnection.new( ['localhost', 30000], ['localhost', 30001],
['localhost', 30002] )
 
# Ensure replica set name
Mongo::ReplSetConnection.new( ['localhost', 30000], :rs_name => "foo" )
 
# Distribute reads to secondaries
Mongo::ReplSetConnection.new( ['localhost', 30000], :read_secondary => true )
 
# Connect directly to a secondary node
Mongo::Connection.new( ['localhost', 30001], :slave_ok => true )
 
# Using Mongo URI
Mongo::Connection.from_uri("mongo://localhost:30001,localhost:30002")
 
# The failover question.
# If a replica set member fails, electing a new master can take
# time. Your application has to allow for this.
 
# See tests.
write_concern.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
require 'rubygems'
require 'mongo'
 
# Write concern can be set on the Connection, DB, Collection,
# or individual operation. Applies to inserts, updates, and deletes.
 
# Writes just write to the socket. Write concen will issue a getlasterror
# command immediately after to flush the socket and ensure that no
# errors were raised on the server.
 
# You can run getlasterror manually. There's a driver helper.
@con = Mongo::Connection.new
@db = @con['test']
 
puts "Get last error"
@db['test']['foo'].save({:foo => "baz"})
p @db.get_last_error
 
# Ensure that write was replicated to a total of two nodes,
# with a 500ms timeout
@db['test']['foo'].save({:foo => "bar"})
@db['test']['foo'].remove
p @db.get_last_error(:w => 0, :wtimeout => 500)
 
puts "Safe mode inheritance"
# These options are specified using :safe
@con = Mongo::Connection.new('localhost', 27017, :safe => true)
@db = @con['test']
@col = @db['foo']
p @db.safe
p @col.safe
 
# Overriding the default safe setting
@col.save({:foo => "baz"}, :safe => false)
 
# More sophisticated safe settings
@con = Mongo::Connection.new('localhost', 27017)
 
@analytics = @con['analytics']
@app = Mongo::DB.new('app', @con, :safe => {:w => 2, :wtimout => 500})
 
puts "Analytics safe mode: #{@analytics.safe}"
puts "App safe mode: #{@app.safe.inspect}"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.