Skip to content

Commit a1e8e81

Browse files
authored
DOCSP-49973 Create a MongoClient (#507)
1 parent 35c6def commit a1e8e81

File tree

4 files changed

+161
-173
lines changed

4 files changed

+161
-173
lines changed

source/connect.txt

Lines changed: 8 additions & 164 deletions
Original file line numberDiff line numberDiff line change
@@ -32,169 +32,13 @@ Connection Guide
3232
Overview
3333
--------
3434

35-
In this guide, you can learn how to connect to a MongoDB instance or
36-
replica set deployment by using the {+driver-short+}.
35+
Learn how to set up a connection and specify connection behavior from your
36+
application to a MongoDB deployment using the {+driver-short+} in the following
37+
sections:
3738

38-
You can use the {+driver-short+} to connect to deployments hosted in the
39-
following environments:
39+
- :ref:`golang-mongoclient`
40+
- :ref:`golang-connection-options`
41+
- :ref:`golang-connection-troubleshooting`
4042

41-
.. include:: /includes/fact-environments.rst
42-
43-
.. _golang-connection-uri:
44-
45-
--------------
46-
Connection URI
47-
--------------
48-
49-
A **connection URI**, also known as a connection string, tells the
50-
driver how to connect to MongoDB and how to behave while connected.
51-
52-
Parts of a Connection URI
53-
~~~~~~~~~~~~~~~~~~~~~~~~~
54-
55-
The following image explains each part of a sample connection URI:
56-
57-
.. figure:: /includes/figures/connection_uri_parts.png
58-
:alt: Each part of the connection string
59-
60-
In this example, we use ``mongodb`` for the protocol, which specifies the
61-
:manual:`Standard Connection String Format
62-
</reference/connection-string/#std-label-connections-standard-connection-string-format>`.
63-
You can also use the :manual:`SRV Connection Format
64-
</reference/connection-string/#srv-connection-format>` if you
65-
want more flexibility of deployment and the ability to change the
66-
servers in rotation without reconfiguring clients.
67-
68-
The next part of the connection string contains your database username and, if
69-
you are using password-based authentication, your password. Replace the value of
70-
``user`` with your database username and ``pass`` with your password. If you are using an
71-
authentication mechanism that does not require a username and password, omit
72-
this part of the connection URI.
73-
74-
The next part of the connection string specifies the hostname or IP address and
75-
port of your MongoDB instance. In the preceding example, we use ``sample.host``
76-
as the hostname and ``27017`` as the port. Replace these values to point to
77-
your MongoDB instance.
78-
79-
The last part of the connection string specifies connection and authentication
80-
options. In the example, we set two connection options:
81-
``maxPoolSize=20`` and ``w=majority``. To learn more about connection
82-
options, see the :ref:`golang-connection-options` guide.
83-
84-
Connection Example
85-
~~~~~~~~~~~~~~~~~~
86-
87-
To connect to MongoDB, you must create a client. A client manages your
88-
connections and runs database commands.
89-
90-
.. tip:: Reuse Your Client
91-
92-
We recommend that you reuse your client across sessions and operations.
93-
You can use the same ``Client`` instance to perform multiple tasks, instead of
94-
creating a new one each time. The ``Client`` type is safe for
95-
concurrent use by multiple `goroutines
96-
<https://www.golang-book.com/books/intro/10>`__.
97-
98-
.. TODO, Add back this line when Connection Pools page is made: To learn more about
99-
how connection pools work in the driver, see the :ref:`Connection Pools guide <golang-connection-pools>`.
100-
101-
You can create a client that uses your connection string and other
102-
client options by passing a ``ClientOptions`` object to the ``Connect()``
103-
method.
104-
105-
To specify your connection URI, pass it to the ``ApplyURI()``
106-
method, which returns a new ``ClientOptions`` instance. To set any other
107-
options, call the relevant helper method from the ``options`` package.
108-
109-
To learn more about connection options, see the
110-
:ref:`Connection Options section <golang-connection-options>`. To learn
111-
more about creating a client, see the API documentation for `Client
112-
<{+api+}/mongo#Client>`__ and `Connect() <{+api+}/mongo#Connect>`__.
113-
114-
You can set the {+stable-api+} version as an option to avoid
115-
breaking changes when you upgrade to a new server version. To
116-
learn more about the {+stable-api+} feature, see the :ref:`{+stable-api+} page
117-
<golang-stable-api>`.
118-
119-
The following code shows how you can create a client that uses an Atlas
120-
connection string and the {+stable-api+} version, connect to MongoDB, and
121-
verify that the connection is successful:
122-
123-
.. _go-connection-example-code:
124-
125-
.. literalinclude:: /includes/fundamentals/code-snippets/srv.go
126-
:language: go
127-
128-
.. tip::
129-
130-
Follow the :ref:`Quick Start guide <golang-connect-to-your-cluster>`
131-
to retrieve your Atlas connection string.
132-
133-
.. note::
134-
135-
To learn about connecting to Atlas Serverless, see the
136-
:ref:`Serverless Instance Limitations page
137-
<atlas-serverless-drivers>` to identify the minimum driver version
138-
required.
139-
140-
--------------------------------
141-
Other Ways to Connect to MongoDB
142-
--------------------------------
143-
144-
If you are connecting to a single MongoDB server instance or replica set
145-
that is not hosted on Atlas, see the following sections to find out how to
146-
connect.
147-
148-
Connect to a MongoDB Server on Your Local Machine
149-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
150-
151-
.. include:: /includes/localhost-connection.rst
152-
153-
To test whether you can connect to your server, replace the connection
154-
string with your localhost connection string in the preceding code example.
155-
156-
Connect to a Replica Set
157-
~~~~~~~~~~~~~~~~~~~~~~~~
158-
159-
A MongoDB replica set deployment is a group of connected instances that
160-
store the same set of data. This configuration provides data
161-
redundancy and high data availability.
162-
163-
To connect to a replica set deployment, specify the hostname and port numbers
164-
of each instance, separated by commas, and the replica set name as the value
165-
of the ``replicaSet`` parameter in the connection string. In the following
166-
example, the hostnames are ``host1``, ``host2``, and ``host3``, and the
167-
port numbers are all ``27017``. The replica set name is ``myRS``.
168-
169-
.. code-block:: none
170-
171-
mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRS
172-
173-
When connecting to a replica set, the driver takes the following actions by default:
174-
175-
- Discovers all replica set members when given the address of any one member.
176-
- Dispatches operations to the appropriate member, such as instructions
177-
to write against the **primary**.
178-
179-
.. tip::
180-
181-
You can specify just one host to connect to a replica set.
182-
However, to ensure connectivity when the specified host
183-
is unavailable, provide the full list of hosts.
184-
185-
Direct Connection
186-
`````````````````
187-
188-
To force operations on the host designated in the connection URI,
189-
specify the ``directConnection`` option. Direct connections exhibit the
190-
following behavior:
191-
192-
- They don't support SRV strings.
193-
- They fail on writes when the specified host is not the **primary**.
194-
- They require you to specify a :manual:`secondary read preference
195-
</core/read-preference/#mongodb-readmode-secondary>` when the
196-
specified host isn't the **primary** node.
197-
198-
.. note:: Replica Set in Docker
199-
200-
.. sharedinclude:: dbx/docker-replica-set.rst
43+
For more information about authenticating with a MongoDB instance, see the
44+
:ref:`golang-authentication` section.

source/connect/mongoclient.txt

Lines changed: 142 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,146 @@ Create a MongoClient
1010
:depth: 2
1111
:class: singlecol
1212

13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: connection string, URI, Atlas, code example
1319

14-
.. TODO
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to connect to a `MongoDB Atlas deployment
24+
<https://www.mongodb.com/docs/atlas>`__, a MongoDB instance, or a replica set
25+
using the {+driver-short+}.
26+
27+
To connect to a MongoDB deployment, you need the following two things:
28+
29+
- **Connection URI**, also known as a *connection string*, which tells the {+driver-short+}
30+
which MongoDB deployment to connect to.
31+
32+
- **MongoClient** object, which creates the connection to and performs operations
33+
on the MongoDB deployment.
34+
35+
You can use ``options.Client()`` to customize the way the {+driver-short+}
36+
behaves while connected to MongoDB.
37+
38+
Connection URI
39+
--------------
40+
41+
A standard connection string includes the following components:
42+
43+
.. list-table::
44+
:widths: 20 80
45+
:header-rows: 1
46+
47+
* - Component
48+
- Description
49+
50+
* - ``mongodb://``
51+
52+
- Required. A prefix that identifies this as a string in the
53+
standard connection format.
54+
55+
* - ``username:password``
56+
57+
- Optional. Authentication credentials. If you include these, the client
58+
authenticates the user against the database specified in ``authSource``.
59+
For more information about the ``authSource`` connection option,
60+
see the :ref:`golang-connection-troubleshooting` guide.
61+
62+
* - ``host[:port]``
63+
64+
- Required. The host and optional port number where MongoDB is running. If you don't
65+
include the port number, the driver uses the default port, ``27017``.
66+
67+
* - ``/defaultauthdb``
68+
69+
- Optional. The authentication database to use if the
70+
connection string includes ``username:password@``
71+
authentication credentials but not the ``authSource`` option.
72+
When you call ``client.db()`` with no argument, this is the database that is used. If you don't include
73+
this component, the client authenticates the user against the ``admin`` database.
74+
75+
* - ``?<options>``
76+
77+
- Optional. A query string that specifies connection-specific
78+
options as ``<name>=<value>`` pairs. See
79+
:ref:`golang-connection-options` for a full description of
80+
these options.
81+
82+
.. tip::
83+
84+
To retrieve a connection string for an Atlas deployment, follow the
85+
:ref:`Quick Start guide <golang-connect-to-your-cluster>`.
86+
87+
For more information about creating a connection string, see :manual:`Connection
88+
Strings </reference/connection-string>` in the MongoDB Server documentation.
89+
90+
Create a Client to Connect to MongoDB Atlas
91+
-------------------------------------------
92+
93+
To connect to MongoDB, you must create a client. A client manages your
94+
connections and runs database commands.
95+
96+
You can create a client that uses your connection string and other client
97+
options by passing a ``ClientOptions`` object to the ``Connect()`` method.
98+
99+
To specify your connection URI, pass it to the ``ApplyURI()`` method, which
100+
returns a new ``ClientOptions`` instance. To set any other options, call the
101+
relevant helper method from the options package.
102+
103+
.. tip:: Reuse Your Client with Connection Pools
104+
105+
We recommend that you reuse your client across sessions and operations by
106+
using a connection pool. You can use the same ``Client`` instance to perform
107+
multiple tasks, instead of creating a new one each time. The ``Client`` type
108+
is safe for concurrent use by multiple `goroutines
109+
<https://go.dev/tour/concurrency/1>`__. To learn more about how connection
110+
pools work in the driver, see the :ref:`golang-connection-pools` guide.
111+
112+
To learn more about connection options, see the :ref:`Connection Options
113+
<golang-connection-options>` section. To learn more about creating a client, see
114+
the API documentation for `Client <{+api+}/mongo#Client>`__ and `Connect()
115+
<{+api+}/mongo#Connect>`__.
116+
117+
You can set the {+stable-api+} version as an option to avoid breaking changes
118+
when you upgrade to a new server version. To learn more about the {+stable-api+}
119+
feature, see the :ref:`{+stable-api+} page <golang-stable-api>`.
120+
121+
.. _go-connection-example-code:
122+
123+
Example
124+
~~~~~~~
125+
126+
The following code shows how you can create a client that uses an Atlas
127+
connection string and the {+stable-api+} version, connects to MongoDB, and verifies
128+
that the connection is successful:
129+
130+
.. literalinclude:: /includes/fundamentals/code-snippets/srv.go
131+
:language: go
132+
:copyable:
133+
:dedent:
134+
135+
Additional Resources
136+
--------------------
137+
138+
For more information about the concepts in this guide, see the following
139+
documentation:
140+
141+
- :manual:`Connection Strings </reference/connection-string>` in the Server
142+
manual
143+
- :manual:`Connection String Options </reference/connection-string>` in the
144+
Server manual
145+
- :atlas:`Driver Connection </driver-connection/>` guide in the Atlas documentation
146+
and select :guilabel:`Go` from the language dropdown
147+
148+
API Documentation
149+
~~~~~~~~~~~~~~~~~
150+
151+
To learn more about the methods and types discussed in this guide, see the
152+
following API Documentation:
153+
154+
- `Client <{+api+}/mongo#Client>`__
155+
- `ClientOptions <{+api+}/mongo/options#ClientOptions>`__

source/includes/fundamentals/code-snippets/srv.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,13 @@ func main() {
1818
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/")
1919
}
2020

21-
// Use the SetServerAPIOptions() method to set the Stable API version to 1
21+
// Uses the SetServerAPIOptions() method to set the Stable API version to 1
2222
serverAPI := options.ServerAPI(options.ServerAPIVersion1)
23+
24+
// Defines the options for the MongoDB client
2325
opts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPI)
2426

25-
// Create a new client and connect to the server
27+
// Creates a new client and connects to the server
2628
client, err := mongo.Connect(opts)
2729

2830
if err != nil {
@@ -34,7 +36,7 @@ func main() {
3436
}
3537
}()
3638

37-
// Send a ping to confirm a successful connection
39+
// Sends a ping to confirm a successful connection
3840
var result bson.M
3941
if err := client.Database("admin").RunCommand(context.TODO(), bson.D{{"ping", 1}}).Decode(&result); err != nil {
4042
panic(err)

source/includes/localhost-connection.rst

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ purposes, complete the following steps:
1111

1212
.. important::
1313

14-
Always secure your MongoDB server from malicious attacks. See our
15-
:manual:`Security Checklist </administration/security-checklist/>` for a
16-
list of security recommendations.
14+
Always secure your MongoDB server from malicious attacks. See the
15+
:manual:`Security Checklist </administration/security-checklist/>` in the
16+
Server manual for a list of security recommendations.
1717

1818
After you successfully start your MongoDB server, specify your connection
1919
string in your driver connection code.
@@ -22,5 +22,6 @@ If your MongoDB Server is running locally, you can use the connection string
2222
``"mongodb://localhost:<port>"`` where ``<port>`` is the port number you
2323
configured your server to listen for incoming connections.
2424

25-
If you want to specify a different hostname or IP address, see our Server
26-
Manual entry on :manual:`Connection Strings </reference/connection-string/>`.
25+
For more information on how to specify a different hostname or IP address, see
26+
:manual:`Connection Strings </reference/connection-string/>` in the Server
27+
manual.

0 commit comments

Comments
 (0)