Skip to content

Instantly share code, notes, and snippets.

@olivoil
Created February 16, 2011 04:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olivoil/828856 to your computer and use it in GitHub Desktop.
Save olivoil/828856 to your computer and use it in GitHub Desktop.
MongoDB code examples for Montreal.rb presentation # in Ruby
## Geolocation [ruby]
# First, create the index on a field containing long-lat values:
articles.create_index([["location", Mongo::GEO2D]])
# Then get a list of the twenty locations nearest to the point 50, 50:
articles.find({"location" => {"$near" => [50, 50]}}, {:limit => 20}).to_a
# collection.index_information() will get you a list of indexes on a Collection
## GridFS [ruby]
@db = Mongo::Connection.new.db('blog')
@grid = Grid.new(@db)
# Saving string data
id = @grid.put("here's some string / binary data")
# Saving IO data overriding attributes and including arbitrary metadata
file = File.open("me.jpg")
id2 = @grid.put(file,
:filename => "my-avatar.jpg"
:content_type => "image/jpg",
:_id => 'a-unique-id-to-use-in-lieu-of-a-random-one',
:chunk_size => 100 * 1024,
:metadata => {'description' => "taken during montreal.rb presentation"},
:safe => true) # MD5 checksum compared on client and server side
# Grid#put returns an object id, which you can use to retrieve the file:
# Get the string we saved
file = @grid.get(id)
image = @grid.get(id2)
# Get the file's metadata
image.filename # => "my-avatar.jpg"
image.content_type # => "image/jpg"
image.file_length # => 502357
image.upload_date # => Mon Feb 15 19:05:30 UTC 2011
## Capped collections [ruby]
@db = Mongo::Connection.new.db('log')
@db.create_collection("tail", :capped => true, :size => 100000, :max => 100)
## [ruby]
# Assume map & reduce to be strings of javascript code
@db = Mongo::Connection.new.db('blog')
@db['articles'].map_reduce(map, reduce, :out => 'articles_tags_aggregation')
## Ruby driver overview [ruby]
gem install mongo
gem install bson_ext
# A Mongo::Connection instance represents a connection to MongoDB.
# Use it to obtain an Mongo:DB instance, which represents a named database.
# The database doesn't have to exist - if it doesn't, MongoDB will create it for you
db = Mongo::Connection.new("localhost", 27017).db("blog")
# Getting a collection
articles = db.collection("articles")
# Inserting a document
article = {
"title" => "MongoDB",
"tags" => ["database", "noSQL"],
"location" => {"long" => 203, "lat" => 102 }
}
articles.insert(article)
# Querying for documents
articles.find(
"created_at" => {"$lte" => Date.today, "$lte" => 3.days.ago},
:fields => ["title", "created_at"]
).each { |article| puts article }
articles.find( "title" => /ruby$/i )
# Updating a document
articles.update({"_id" => article["_id"]}, {"$set" => {"title" => "MongoDB ♥ Ruby")
# Running commands
command = {
'findandmodify' => 'articles',
'query' => { 'state' => 'draft' },
'sort' => { 'created_at' => -1 },
'update' => { '$set' => { 'state' => 'published' } }
}
db.command( command )
## Write concern
# The ruby driver implements a safe mode
# Wait for a response from the database
articles.save( { :title => 'foo' }, :safe => true )
# Wait until 2 servers have recorded the write
articles.save( { :title => 'foo' }, :safe => { :w => 2 } )
# and time out if the replication can't be completed in 200 milliseconds
articles.save( { :title => 'foo' }, :safe => { :w => 2, :wtimeout => 200 } )
# and flush all pending writes to datafiles without waiting for the default interval (60 seconds)
articles.save( { :title => 'foo' }, :safe => { :w => 2, :wtimeout => 200, :fsync => true } )
# sets the safe mode for all writes from a connection
connection = Mongo::Connection.new( "localhost", 27017, :safe => {:w => 3} )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment