mongo-ruby-driver/examples/cursor.rb

48 lines
1.2 KiB
Ruby
Raw Normal View History

2009-02-03 19:19:30 +00:00
$LOAD_PATH[0,0] = File.join(File.dirname(__FILE__), '..', 'lib')
require 'mongo'
require 'pp'
include Mongo
2009-02-03 19:19:30 +00:00
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
2009-02-03 19:19:30 +00:00
puts "Connecting to #{host}:#{port}"
db = Connection.new(host, port).db('ruby-mongo-examples')
2009-02-03 19:19:30 +00:00
coll = db.collection('test')
# Erase all records from collection, if any
2010-01-05 23:14:48 +00:00
coll.remove
2009-02-03 19:19:30 +00:00
# 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
2009-12-16 19:03:15 +00:00
first_object = coll.find().next_document
2009-02-03 19:19:30 +00:00
2009-12-16 19:03:15 +00:00
# next_document returns nil if there are no more objects that match
2009-02-03 19:19:30 +00:00
cursor = coll.find()
2009-12-16 19:03:15 +00:00
obj = cursor.next_document
2009-02-03 19:19:30 +00:00
while obj
pp obj
2009-12-16 19:03:15 +00:00
obj = cursor.next_document
2009-02-03 19:19:30 +00:00
end
# Destroy the collection
coll.drop