Ruby, MongoDB, and Compose

Quick note: In this example, we are assuming that your Compose connection string is set in an environment variable MONGODB_URL, like this:

MONGODB_URL="mongodb://user:[email protected]:port/db_name"

If you are using Ruby (along with frameworks like Ruby on Rails, Sinatra, etc.), you can start out by installing the mongo (2.x) gem. It should go without saying, but you will need RubyGems.

Connecting with TLS/SSL

TLS/SSL connections to Compose MongoDB are usually verified by the use of Let's Encrypt certificates. This means that you only need to set the connection string.

require 'mongo'

Mongo::Logger.logger.level = ::Logger::FATAL

options = { ssl:true, ssl_verify: true }
client=Mongo::Client.new(ENV['MONGODB_URL'], options )

db = client.database
collections = db.collection_names
puts collections # ["coll1", "coll2", ...]

The Logger line mutes the driver's debug messages (there's a lot of them). Comment it out if you want to see more.

Connecting with TLS/SSL and self-signed certificates

Some Compose MongoDB deployments use self-signed certificates, such as Compose Enterprise MongoDB. With the certificate saved locally on disk, this example uses the MONGODB_CERT_PATH environment variable to pass the path to the certificate to the application. If it is not set, the example automatically assumes that the connection string is using a Let's Encrypt certificate.

require 'mongo'

Mongo::Logger.logger.level = ::Logger::FATAL

options = { ssl:true, ssl_verify: true }
options["ssl_ca_cert"]=ENV['MONGODB_CERT_PATH'] if ENV['MONGODB_CERT_PATH'] 
client=Mongo::Client.new(ENV['MONGODB_URL'], options )

db = client.database
collections = db.collection_names
puts collections # ["coll1", "coll2", ...]

Connecting without TLS/SSL

If your MongoDB deployment is configured to not use TLS/SSL, the connection process is even simpler, albeit less secure.

require 'mongo'

Mongo::Logger.logger.level = ::Logger::FATAL

client=Mongo::Client.new(ENV['MONGODB_URL'])

db = client.database
collections = db.collection_names
puts collections # ["coll1", "coll2", ...]

We do recommend, though, that for your own security you consider using TLS/SSL on your MongoDB deployment.


Still Need Help?

If this article didn't solve things, summon a human and get some help!