Docs Menu
Docs Home
/ / /
Ruby MongoDB Driver
/

Connect to MongoDB

1

Navigate to your quickstart.rb file in the ruby-quickstart directory. Copy and paste the following code below the Bundler code from the Download and Install step of this tutorial. This code connects to MongoDB and queries the movies collection in the sample_mflix database.

uri = '<connection string>'
begin
client = Mongo::Client.new(uri)
database = client.use('sample_mflix')
movies = database[:movies]
# Queries for a movie that has the title 'Back to the Future'
query = { title: 'Back to the Future' }
movie = movies.find(query).first
# Prints the movie document
puts movie
ensure
client&.close
end
2

Replace the <connection string> placeholder with the connection string that you copied from the Create a Connection String step of this tutorial.

3

From your ruby-quickstart directory, run the following shell command to run the application:

ruby quickstart.rb

The command line output contains details about the retrieved movie document:

{"_id"=>BSON::ObjectId('...'), "plot"=>"A young man is accidentally sent
30 years into the past in a time-traveling DeLorean invented by his friend,
Dr. Emmett Brown, and must make sure his high-school-age parents unite
in order to save his own existence.", ...
"title"=>"Back to the Future", ...

If you encounter an error or see no output, ensure that you specified the correct connection string in the quickstart.rb file and that you loaded the sample data.

After you complete these steps, you have a working application that uses the driver to connect to your MongoDB deployment, runs a query on the sample data, and prints out the result.

Note

If you run into issues on this step, ask for help in the MongoDB Community Forums or submit feedback by using the Rate this page tab on the right side of this page.

Back

Create a Connection String