Skip to content

Instantly share code, notes, and snippets.

@mdirolf
Forked from jhancock/gist:167028
Created August 13, 2009 14:01
Show Gist options
  • Save mdirolf/167194 to your computer and use it in GitHub Desktop.
Save mdirolf/167194 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'mongo'
require 'pp'
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
port = ENV['MONGO_RUBY_DRIVER_PORT'] || XGen::Mongo::Driver::Mongo::DEFAULT_PORT
puts "Connecting to #{host}:#{port}"
db = XGen::Mongo::Driver::Mongo.new(host, port).db('jon')
coll = db.collection('test')
puts
puts ">> clear collection jon:test"
coll.clear
puts "Count of jon:test #{coll.count}"
puts
puts ">> insert an object with attributes sample1 and when"
#object = OrderedHash['sample1' => "hello", 'when' => Time.now]
#puts "before save of new object"
#pp object
oid = coll.save({'sample1' => "hello", 'when' => Time.now})
puts "returned ObjectID"
pp oid
puts "all object"
coll.find().each { |doc| puts doc.inspect }
puts
puts ">> find the object just inserted"
puts "Count of jon:test #{coll.count}"
cursor = coll.find()
object = cursor.next_object()
puts "this object should have the same ObjectID as above"
pp object
puts
puts ">> add attribute sample2 to the object just retreived"
object['sample2'] = "goodbye"
pp object
puts "Save changes"
coll.save(object)
puts
puts ">> retreive the object which should have sample1, sample2, and when"
puts "Count of jon:test #{coll.count}"
cursor = coll.find
object = cursor.next_object
pp object
puts
puts ">> retreive part of the object, only sample1"
puts "Count of jon:test #{coll.count}"
cursor = coll.find({}, {:fields => ['sample1']})
object = cursor.next_object
pp object
puts
puts ">> modify attribute sample2 to the object just retreived which should only have sample1 loaded"
pp object
coll.repsert(object, {"$set" => {"sample2" => "hello again"}})
#coll.save(object)
puts
puts ">> retreive the whole object, so 'when' got clobbered!!! How should I have done this preserve the other attribs in the db?"
puts "Count of jon:test #{coll.count}"
cursor = coll.find
object = cursor.next_object
pp object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment