The MongoDB Ruby driver is the `mongo` gem. It lets Ruby applications connect to a MongoDB database, select collections, and run queries directly from Ruby code. A connection string can point to an Atlas deployment or a self-hosted cluster. section 3.7 section 3.4
To run a basic query:
- Install the gem with `gem install mongo`, or add `gem "mongo", "~> 2"` to your Gemfile. section 3.7
- Obtain your connection string from the Atlas interface or CLI, and use it to create a `Mongo::Client`. section 3.7
- Select a database and collection, then query with a Ruby hash—for example, `routes.find('src_airport' => 'JFK').first`. section 3.7
- Handle errors and close the client in an `ensure` block, including when the query fails. section 3.7
Listing 3.11 Ruby MongoDB driver example
require 'mongo' #1
# Replace the uri string with your MongoDB connection string.
uri = "< connection string uri >" #2
# Create a MongoClient instance.
client = Mongo::Client.new(uri) #3
# Define a block of code to execute.
begin
# Connect to the database.
database = client.use("sample_training") #4
# Reference a collection
routes = database[:routes] #5
# Query to find routes from JFK airport.
query = { 'src_airport' => 'JFK' } #6
route = routes.find(query).first #7
puts route #8
rescue => error
puts error.message #9
ensure
# Ensure that we close the database connection
client.close #10
end
The complete Ruby script connects to `sample_training`, finds a route departing JFK, prints it, and closes the client. section 3.7
For Atlas, use driver version 2.6.1 or later for improved TLS connection performance. The driver supports TLS connections and SCRAM or X.509 authentication; these capabilities require a working Ruby `openssl` extension. Beyond ordinary queries, the gem is also used in a vector-search example with category and price prefilters. section 3.7 section 12.4.3
