File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -327,7 +327,41 @@ URI option:
327
327
# Or using the URI syntax:
328
328
Mongo::Client.new("mongodb://1.2.3.4:27017/mydb?loadBalanced=true&connect=load_balanced")
329
329
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
330
343
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
331
365
332
366
.. _srv-uri-notes:
333
367
You can’t perform that action at this time.
0 commit comments