Skip to content

Commit 7f52414

Browse files
authored
RUBY-3215: Update client connection example to include Atlas (#2699)
* RUBY-3215: Update client connection example to include Atlas * RUBY-3215: Fixed typo in codeblock
1 parent 5defc85 commit 7f52414

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

docs/reference/create-client.txt

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,41 @@ URI option:
327327
# Or using the URI syntax:
328328
Mongo::Client.new("mongodb://1.2.3.4:27017/mydb?loadBalanced=true&connect=load_balanced")
329329

330+
MongoDB Atlas Connection
331+
------------------------
332+
333+
To connect to a MongoDB deployment on Atlas, first create a ``Mongo::Client`` instance using your
334+
cluster's connection string and other client options.
335+
336+
You can set the `Stable API <https://www.mongodb.com/docs/manual/reference/stable-api/>`_ version as
337+
a client option to avoid breaking changes when you upgrade to a new server version.
338+
339+
The following code shows how you can specify the connection string and the Stable API client option
340+
when connecting to a MongoDB deployment and verify that the connection is successful:
341+
342+
.. code-block:: ruby
330343

344+
require 'mongo'
345+
346+
# Replace the placeholders with your credentials
347+
uri = "mongodb+srv://<username>:<password>@cluster0.sample.mongodb.net/?retryWrites=true&w=majority"
348+
349+
# Set the server_api field of the options object to Stable API version 1
350+
options = { server_api: { version: "1" } }
351+
352+
# Create a new client and connect to the server
353+
client = Mongo::Client.new(uri, options)
354+
355+
# Send a ping to confirm a successful connection
356+
begin
357+
admin_client = client.use('admin')
358+
result = admin_client.database.command(ping: 1).documents.first
359+
puts "Pinged your deployment. You successfully connected to MongoDB!"
360+
rescue Mongo::Error::OperationFailure => ex
361+
puts ex
362+
ensure
363+
client.close
364+
end
331365

332366
.. _srv-uri-notes:
333367

0 commit comments

Comments
 (0)