Connecting to a replica set
Connecting to a replica set is not fundamentally different to connecting to a single server. In this section, we will show some examples using the official mongo-ruby-driver.
First we need to set our host and options objects:
client_host = ['hostname:port'] client_options = { database: 'signals', replica_set: 'xmr_btc' }
In the preceding example, we are getting ready to connect to host:port
hostname, in database signals in the replica_set xmr_btc
.
Calling the initializer on Mongo::Client
will now return a client object that contains a connection to our replica set and database:
client = Mongo::Client.new(client_host, client_options)
The client object then has the same options as it has when connecting to a single server.
Note
MongoDB uses auto-discovery after connecting to our client_host
to identify the other members of our replica set, be they the primary or secondaries.
The client object should be used as a singleton, created once and reused across our code base...