From 654ea133059dac989b53f4a5205e499e6f58ea3b Mon Sep 17 00:00:00 2001 From: Jim Menard Date: Tue, 3 Feb 2009 14:19:30 -0500 Subject: [PATCH] more examples --- examples/admin.rb | 1 + examples/cursor.rb | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 examples/cursor.rb diff --git a/examples/admin.rb b/examples/admin.rb index ecd3fb2..aec783f 100644 --- a/examples/admin.rb +++ b/examples/admin.rb @@ -35,6 +35,7 @@ admin = db.admin # Validate returns a hash if all is well or raises an exception if there is a # problem. info = admin.validate_collection(coll.name) +puts "valid = #{info['ok']}" puts info['result'] # Destroy the collection diff --git a/examples/cursor.rb b/examples/cursor.rb new file mode 100644 index 0000000..a7896ed --- /dev/null +++ b/examples/cursor.rb @@ -0,0 +1,47 @@ +$LOAD_PATH[0,0] = File.join(File.dirname(__FILE__), '..', 'lib') +require 'mongo' +require 'pp' + +include XGen::Mongo::Driver + +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 = Mongo.new(host, port).db('ruby-mongo-examples') +coll = db.collection('test') + +# Erase all records from collection, if any +coll.clear + +# Insert 3 records +3.times { |i| coll.insert({'a' => i+1}) } + +# Cursors don't run their queries until you actually attempt to retrieve data +# from them. + +# Find returns a Cursor, which is Enumerable. You can iterate: +coll.find().each { |row| pp row } + +# You can turn it into an array +array = coll.find().to_a + +# You can iterate after turning it into an array (the cursor will iterate over +# the copy of the array that it saves internally.) +cursor = coll.find() +array = cursor.to_a +cursor.each { |row| pp row } + +# You can get the next object +first_object = coll.find().next_object + +# next_object returns nil if there are no more objects that match +cursor = coll.find() +obj = cursor.next_object +while obj + pp obj + obj = cursor.next_object +end + +# Destroy the collection +coll.drop