Connecting using Ruby

Ruby was one of the first languages to have support from MongoDB with an official driver. The official MongoDB Ruby driver on GitHub is the recommended way to connect to a MongoDB instance. Perform the following steps to connect MongoDB using Ruby:

  1. Installation is as simple as adding it to the Gemfile, as shown in the following example:
gem 'mongo', '~> 2.6'
You need to install Ruby, then install RVM from https://rvm.io/rvm/install, and finally run gem install bundler for this.

  1. Then, in our class, we can connect to a database, as shown in the following example:
require 'mongo'
client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'test')
  1. This is the simplest example possible: connecting to a single database instance called test in our localhost. In most use cases, we would at least have a replica set to connect to, as shown in the following snippet:
client_host = ['server1_hostname:server1_ip, server2_hostname:server2_ip']
client_options = {
database: 'YOUR_DATABASE_NAME',
replica_set: 'REPLICA_SET_NAME',
user: 'YOUR_USERNAME',
password: 'YOUR_PASSWORD'
}
client = Mongo::Client.new(client_host, client_options)
  1. The client_host servers are seeding the client driver with servers to attempts to connect. Once connected, the driver will determine the server that it has to connect to according to the primary/secondary read or write configuration. The replica_set attribute needs to match REPLICA_SET_NAME to be able to connect.
  2. user and password are optional, but highly recommended in any MongoDB instance. It's good practice to enable authentication by default in the mongod.conf file and we will learn more about this in Chapter 8Monitoring, Backup, and Security.
  3. Connecting to a sharded cluster is similar to a replica set, with the only difference being that, instead of supplying the server host/port, we need to connect to the MongoDB process that serves as the MongoDB router.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset