Using MongoDB with Ruby: Using a Collection

In the following subsections we shall connect to MongoDB server, get database information, and create a collection.

1. Creating a Connection with MongoDB

In this section we shall connect with MongoDB Server using a Ruby script.

  1. Create a directory called C:\Ruby21-x64\mongodbscripts for Ruby scripts.
  2. Create a Ruby script connection.rb in the C:\Ruby21-x64\mongodbscripts directory. In the script add a require statement for the mongo gem. Add an include statement for the Mongo namespace.

require ‘mongo’

include ‘Mongo’

The Client class provides several attributes and methods for getting information about the connection. Some of the attributes are discussed in Table 4-2.

Some of the salient methods in the Client class are discussed in Table 4-3.

The syntax for Client class constructor is as follows.

initialize(addresses_or_uri, options = {})

The parameters for the constructor are discussed in Table 4-4.

Some of the options supported by Client class constructor are discussed in Table 4-5.

  1. In the connection.rb script create a connection with MongoDB Server using one of the Client class constructors. The host and port may be specified explicitly; if either is not specified the default value is used. If the host and port are not specified the default. host and port are localhost:27017. The default database is test. The following are some of the different applications of the Client class constructors.

client =Mongo::Client.new

client =Mongo::Client.new([ ‘127.0.0.1:27017’ ], :database => ‘test’)

client =Mongo::Client.new([ ‘127.0.0.1:27017’ ], :database => ‘test’,

:connect => :direct)

client =Mongo::Client.new(‘mongodb://127.0.0.1:27017/test’)

client = Mongo::Client.new([ ‘127.0.0.1:27017’ ], :database => ‘test’,

:max_pool_size => 20, :connection_timeout => 60)

The IPv4 address of the host may be specified instead of localhost.

client =Mongo::Client.new([t192.l68.1.72:27017′ ], :database => ‘test’)

The Client class attributes’ values may be output, and instance methods may be invoked using the Client class instance.

The connection.rb script for connecting to MongoDB server, invoking some of the methods, and outputting some of the attribute values are listed:

require ‘mongo’ include Mongo

#client =Mongo::Client.new([ ‘127.0.0.1:27017’ ], :database => ‘test’)

#client =Mongo::Client.new([ ‘127.0.0.1:27017’ ], :database => ‘test’, :connect => :direct)

#client =Mongo::Client.new(‘mongodb://127.0.0.1:27017/test’)

client = Mongo::Client.new([ ‘127.0.0.1:27017’ ], :database => ‘test’, :max_pool_size => 20,

:connection_timeout => 60)

print “Cluster: “

print client.cluster

print “\n”

print “Configuration Options: ”

print client.options

print “\n”

print “Read Preference: ”

print client.read_preference

print “\n”

print “Write Concern : ”

print client.write_concern

print “\n”

  1. From the C:\Ruby21-x64\mongodbscripts directory run the connection.rb

script with the following command.

>ruby connection.rb

The output from the connection.rb script is shown in Figure 4-10

2. Connecting to a Database

A MongoDB database instance is represented with the Mongo::Database class. In this section we shall create some MongoDB database instances and get other information about databases.

  1. Create a Ruby script db.rb in the C:\Ruby21-x64\mongodbscripts directory. The Database class provides several instance attributes and methods. The attributes are discussed in Table 4-6.

Some of the instance methods supported by the Database class are discussed in Table 4-7.

The Database class constructor has the following signature.

initialize(client, name, options = {})

The constructor parameters are the same as the class attributes and are discussed in Table 4-6.

  1. In the db.rb script create a Client instance as before.

client =Mongo::Client.new([ ‘127.0.0.1:27017’ ], :database => ‘test’)

  1. Obtain the database from the Client instance using the database attribute and output the database name using the name attribute of the database instance.

db=client.database print db.name

  1. Output the client and the configuration options using the client and options attributes.

print db.client print db.options

  1. Output the database names using the database_names() method of the Client class.

print client.database_names

  1. Iterate over the collection returned by the list_databases() method of the Client instance to output information about each database.

client.list_databases.each { |info| puts info.inspect }

  1. To use a particular database invoke the use(database) method of the Client instance. For example, the database may be set to mongo database as follows.

client=client.use(:mongo)

  1. Subsequent to setting the database to mongo, output the database name again to verify that the database has been set. Drop a database using the drop() method.

print db.drop

The db.rb script is listed as follows.

require ‘mongo’ include Mongo

client =Mongo::Client.new([ ‘127.0.0.1:27017’ ], :database => ‘test’)

print “Database Connected to: “

db=client.database

print db.name

print “\n”

print “Database Client: ”

print db.client

print “\n”

print “Database Options: ”

print db.options

print “\n”

print “Database Names: ”

print client.database_names

print “\n”

print “Database Info: “

client.list_databases.each { |info| puts info.inspect }

print “\n”

print “Use Database mongo: “

client=client.use(:mongo)

print “\n”

print “Database Connected to: ”

db=client.database print db.name

print “\n”

print “Use Database mongo: ”

client=client.use(:local)

print “\n”

print “Database Connected to: ”

db=client.database print db.name

print “\n”

print db.drop

  1. Run the db.rb script with the following command.

>ruby db.rb

The output from the db.rb script is shown in Figure 4-11. What should be noted in the output is that the mongo database instance does not get listed with database_names subsequent to setting the database instance to mongo because the database instance has not been accessed.

After a database instance local has been dropped the database does not get listed in Mongo shell with show dbs command as shown in Figure 4-12.

As we shall be using the local database in subsequent sections create the local database with the following commands in Mongo shell.

>use local

>db.createCollection(“local”)

3. Creating a Collection

The Mongo::Database class provides several methods for collections, which are discussed in Table 4-7. A collection is represented with the Mongo::Collection class. The Collection class provides several instance attributes and methods. The attributes are discussed in Table 4-8.

Some of the instance methods supported by the Collection class are discussed in Table 4-9.

The Collection class constructor has the following signature.

initialize(database, name, options = {})

The constructor parameters are the same as the class attributes.

  1. First, create a Ruby script collection.rb in the C:\Ruby21-x64\mongodbscripts directory and include the mongo gem and the Mongo namespace as before.
  1. Create a Client instance for a connection to MongoDB and subsequently get the database instance for local database.

client =Mongo::Client.new([ ‘127.0.0.1:27017’ ], :database => ‘test’)

  1. Using the use(database) instance method in Client class. set the database to local.

client=client.use(:local)

  1. Output the collection names using the collection_names() method in Mongo::Database class.

print db.collection_names({})

  1. Output info on all the collections using the list_collections() method. db.list_collections.each { |info| puts info.inspect }
  2. Output the array of all the collections using the collections() method. db.collections.each { |info| puts info.inspect }
  3. Using the Database class instance method [], set the collection to users as follows.

collection=db[:users]

  1. Output the collection name using the name attribute in Collection class. print collection.name
  2. The database associated with a collection may be output using the database attribute.

print collection.database

  1. Find if a collection is capped using the capped? method. print collection.capped?
  2. Output the namespace using the namespace() method. print collection.namespace
  3. The collection() instance method in Database class does not create a collection until the collection is accessed. To demonstrate, invoke the collection() method on a collection that does not exist in the database, for example, the mongodb collection.

collection=db.collection(“mongodb”)

  1. Subsequently, output the collection names. print

db.collection_names({})

  1. To create the mongodb collection, invoke the create() method. collection.create
  2. Invoke the collection_names({}) method in Database again. As the create() method creates the collection the mongodb collection gets listed when the collection.rb script is run as shown in Figure 4-13.
  3. To drop the current collection, invoke the drop() method. collection.drop
  4. List the collection names subsequent to dropping the collection. When the collection.rb script is run the mongodb collection does not get listed as shown in Figure 4-13. The collection.rb script is listed:

require ‘mongo’

include Mongo

client =Mongo::Client.new([ ‘127.0.0.1:27017’ ], :database => ‘test’)

print “Use Database local: ”

client=client.use(:local)

print “\n”

print “Database Connected to: “

db=client.database print db.name

print “\n”

print “Collection Names: ”

print db.collection_names({})

print “\n”

print “Collections List: “

db.list_collections.each { |info| puts info.inspect }

print “\n”

print “Collections Array: “

db.collections.each { |info| puts info.inspect }

print “\n”

collection=db[:users]

print “Collection name: ”

print collection.name

print “\n”

print “Collection Database: ”

print collection.database

print “\n”

print “Collection options: ”

print collection.options

print “\n”

print “Capped: ”

print collection.capped?

print “\n”

print “Namespace: “

print collection.namespace

print “\n”

## Does not create a collection till the collection is accessed.

collection=db.collection(“mongodb”)

print “Collection Names: “

print db.collection_names({})

print “\n”

collection.create

print “Collection Names: ”

print db.collection_names({})

print “\n”

print “Drop collection mongodb “

print “\n”

collection.drop

print “Collection Names: “

print db.collection_names

print “\n”

  1. Run the collection.rb script with the following command.

>ruby collection.rb

The output from the collection.rb script is shown in Figure 4-13.

Source: Vohra Deepak (2015), Pro MongoDB™ Development, Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *