You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
require'mongo'require'pp'includeMongohost=ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'port=ENV['MONGO_RUBY_DRIVER_PORT'] || MongoClient::DEFAULT_PORTputs"Connecting to #{host}:#{port}"client=MongoClient.new(host,port)db=client.db('ruby-mongo-examples')coll=db.create_collection('test')# Erase all records from collection, if anycoll.removeadmin=client['admin']# Profiling level set/getputs"Profiling level: #{admin.profiling_level}"# Start profiling everythingadmin.profiling_level=:all# Read records, creating a profiling eventcoll.find().to_a# Stop profilingadmin.profiling_level=:off# Print all profiling infoppadmin.profiling_info# Validate returns a hash if all is well and# raises an exception if there is a problem.info=db.validate_collection(coll.name)puts"valid = #{info['ok']}"putsinfo['result']# Destroy the collectioncoll.drop
Capped Collection Example
require'mongo'includeMongohost=ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'port=ENV['MONGO_RUBY_DRIVER_PORT'] || MongoClient::DEFAULT_PORTputs"Connecting to #{host}:#{port}"db=MongoClient.new(host,port).db('ruby-mongo-examples')db.drop_collection('test')# A capped collection has a max size and, optionally, a max number of records.# Old records get pushed out by new ones once the size or max num records is reached.coll=db.create_collection('test',:capped=>true,:size=>1024,:max=>12)100.times{ |i| coll.insert('a'=>i+1)}# We will only see the last 12 recordscoll.find().each{ |row| prow}coll.drop
Working with Cursors
require'mongo'require'pp'includeMongohost=ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'port=ENV['MONGO_RUBY_DRIVER_PORT'] || MongoClient::DEFAULT_PORTputs"Connecting to #{host}:#{port}"db=MongoClient.new(host,port).db('ruby-mongo-examples')coll=db.collection('test')# Erase all records from collection, if anycoll.remove# Insert 3 records3.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| pprow}# 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_acursor.each{ |row| pprow}# You can get the next objectfirst_object=coll.find().next_document# next_document returns nil if there are no more objects that matchcursor=coll.find()obj=cursor.next_documentwhileobjppobjobj=cursor.next_documentend# Destroy the collectioncoll.drop
GridFS
defassertraise"Failed!"unlessyieldendrequire'mongo'includeMongohost=ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'port=ENV['MONGO_RUBY_DRIVER_PORT'] || MongoClient::DEFAULT_PORTputs"Connecting to #{host}:#{port}"db=MongoClient.new(host,port).db('ruby-mongo-examples')data="hello, world!"grid=Grid.new(db)# Write a new file. data can be a string or an io object responding to #read.id=grid.put(data,:filename=>'hello.txt')# Read it and print out the contentsfile=grid.get(id)putsfile.read# Delete the filegrid.delete(id)begingrid.get(id)rescue=>eassert{e.class == Mongo::GridError}end# Metadataid=grid.put(data,:filename=>'hello.txt',:content_type=>'text/plain',:metadata=>{'name'=>'hello'})file=grid.get(id)pfile.content_typepfile.metadata.inspectpfile.chunk_sizepfile.file_lengthpfile.filenamepfile.data
Gathering Information
require'mongo'includeMongohost=ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'port=ENV['MONGO_RUBY_DRIVER_PORT'] || MongoClient::DEFAULT_PORTputs"Connecting to #{host}:#{port}"db=MongoClient.new(host,port).db('ruby-mongo-examples')coll=db.collection('test')# Erase all records from collection, if anycoll.remove# Insert 3 records3.times{ |i| coll.insert({'a'=>i+1})}# Collection names in databasepdb.collection_names# More information about each collectionpdb.collections_info# Index informationcoll.create_index('a')pdb.index_information('test')# Destroy the collectioncoll.drop
Queries
require'mongo'require'pp'includeMongohost=ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'port=ENV['MONGO_RUBY_DRIVER_PORT'] || MongoClient::DEFAULT_PORTputs"Connecting to #{host}:#{port}"db=MongoClient.new(host,port).db('ruby-mongo-examples')coll=db.collection('test')# Remove all records, if anycoll.remove# Insert three recordscoll.insert('a'=>1)coll.insert('a'=>2)coll.insert('b'=>3)coll.insert('c'=>'foo')coll.insert('c'=>'bar')# Count.puts"There are #{coll.count} records."# Find all records. find() returns a Cursor.puts"Find all records:"ppcursor=coll.find.to_a# Print them. Note that all records have an _id automatically added by the# database. See pk.rb for an example of how to use a primary key factory to# generate your own values for _id.puts"Print each document individually:"ppcursor.each{ |row| pprow}# See Collection#find. From now on in this file, we won't be printing the# records we find.puts"Find one record:"ppcoll.find('a'=>1).to_a# Find records sort by 'a', skip 1, limit 2 records.# Sort can be single name, array, or hash.puts"Skip 1, limit 2, sort by 'a':"ppcoll.find({},{:skip=>1,:limit=>2,:sort=>'a'}).to_a# Find all records with 'a' > 1. There is also $lt, $gte, and $lte.coll.find({'a'=>{'$gt'=>1}})coll.find({'a'=>{'$gt'=>1,'$lte'=>3}})# Find all records with 'a' in a set of values.puts"Find all records where a is $in [1, 2]:"ppcoll.find('a'=>{'$in'=>[1,2]}).to_aputs"Find by regex:"ppcoll.find({'c'=>/f/}).to_a# Print query explanationputs"Print an explain:"ppcoll.find({'c'=>/f/}).explain# Use a hint with a query. Need an index. Hints can be stored with the# collection, in which case they will be used with all queries, or they can be# specified per query, in which case that hint overrides the hint associated# with the collection if any.coll.create_index('c')coll.hint='c'puts"Print an explain with index:"ppcoll.find('c'=>/[f|b]/).explainputs"Print an explain with natural order hint:"ppcoll.find({'c'=>/[f|b]/},:hint=>'$natural').explain
Replica Sets
# This code assumes a running replica set with at least one node at localhost:27017.require'mongo'includeMongocons=[]10.timesdocons << MongoReplicaSetClient(['localhost:27017'],:read=>:secondary)endports=cons.mapdo |con|
con.read_pool.portendputs"These ten connections will read from the following ports:"pportscons[rand(10)]['foo']['bar'].remove100.timesdo |n|
cons[rand(10)]['foo']['bar'].insert({:a=>n})end100.timesdo |n|
pcons[rand(10)]['foo']['bar'].find_one({:a=>n})end
Simple
require'rubygems'require'mongo'includeMongohost=ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'port=ENV['MONGO_RUBY_DRIVER_PORT'] || MongoClient::DEFAULT_PORTputs"Connecting to #{host}:#{port}"db=MongoClient.new(host,port).db('ruby-mongo-examples')coll=db.collection('test')# Erase all records from collection, if anycoll.remove# Insert 3 records3.times{ |i| coll.insert({'a'=>i+1})}puts"There are #{coll.count()} records in the test collection. Here they are:"coll.find().each{ |doc| putsdoc.inspect}# Destroy the collectioncoll.drop
Strict Mode
require'mongo'includeMongohost=ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'port=ENV['MONGO_RUBY_DRIVER_PORT'] || MongoClient::DEFAULT_PORTputs"Connecting to #{host}:#{port}"db=MongoClient.new(host,port).db('ruby-mongo-examples')db.drop_collection('does-not-exist')db.create_collection('test')db.strict=truebegin# Can't reference collection that does not existdb.collection('does-not-exist')puts"error: expected exception"rescue=>exputs"expected exception: #{ex}"endbegin# Can't create collection that already existsdb.create_collection('test')puts"error: expected exception"rescue=>exputs"expected exception: #{ex}"enddb.strict=falsedb.drop_collection('test')
Types
require'mongo'require'pp'includeMongohost=ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'port=ENV['MONGO_RUBY_DRIVER_PORT'] || MongoClient::DEFAULT_PORTputs"Connecting to #{host}:#{port}"db=MongoClient.new(host,port).db('ruby-mongo-examples')coll=db.collection('test')# Remove all records, if anycoll.remove# Insert record with all sorts of valuescoll.insert('array'=>[1,2,3],'string'=>'hello','hash'=>{'a'=>1,'b'=>2},'date'=>Time.now,# milliseconds only; microseconds are not stored'oid'=>ObjectID.new,'binary'=>Binary.new([1,2,3]),'int'=>42,'float'=>33.33333,'regex'=>/foobar/i,'boolean'=>true,'where'=>Code.new('this.x == 3'),'dbref'=>DBRef.new(coll.name,ObjectID.new),'null'=>nil,'symbol'=>:zildjian)ppcoll.find().next_documentcoll.remove