diff --git a/source/connect.txt b/source/connect.txt index 5be7092e..81615978 100644 --- a/source/connect.txt +++ b/source/connect.txt @@ -32,169 +32,13 @@ Connection Guide Overview -------- -In this guide, you can learn how to connect to a MongoDB instance or -replica set deployment by using the {+driver-short+}. +Learn how to set up a connection and specify connection behavior from your +application to a MongoDB deployment using the {+driver-short+} in the following +sections: -You can use the {+driver-short+} to connect to deployments hosted in the -following environments: +- :ref:`golang-mongoclient` +- :ref:`golang-connection-options` +- :ref:`golang-connection-troubleshooting` -.. include:: /includes/fact-environments.rst - -.. _golang-connection-uri: - --------------- -Connection URI --------------- - -A **connection URI**, also known as a connection string, tells the -driver how to connect to MongoDB and how to behave while connected. - -Parts of a Connection URI -~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following image explains each part of a sample connection URI: - -.. figure:: /includes/figures/connection_uri_parts.png - :alt: Each part of the connection string - -In this example, we use ``mongodb`` for the protocol, which specifies the -:manual:`Standard Connection String Format -`. -You can also use the :manual:`SRV Connection Format -` if you -want more flexibility of deployment and the ability to change the -servers in rotation without reconfiguring clients. - -The next part of the connection string contains your database username and, if -you are using password-based authentication, your password. Replace the value of -``user`` with your database username and ``pass`` with your password. If you are using an -authentication mechanism that does not require a username and password, omit -this part of the connection URI. - -The next part of the connection string specifies the hostname or IP address and -port of your MongoDB instance. In the preceding example, we use ``sample.host`` -as the hostname and ``27017`` as the port. Replace these values to point to -your MongoDB instance. - -The last part of the connection string specifies connection and authentication -options. In the example, we set two connection options: -``maxPoolSize=20`` and ``w=majority``. To learn more about connection -options, see the :ref:`golang-connection-options` guide. - -Connection Example -~~~~~~~~~~~~~~~~~~ - -To connect to MongoDB, you must create a client. A client manages your -connections and runs database commands. - -.. tip:: Reuse Your Client - - We recommend that you reuse your client across sessions and operations. - You can use the same ``Client`` instance to perform multiple tasks, instead of - creating a new one each time. The ``Client`` type is safe for - concurrent use by multiple `goroutines - `__. - -.. TODO, Add back this line when Connection Pools page is made: To learn more about - how connection pools work in the driver, see the :ref:`Connection Pools guide `. - -You can create a client that uses your connection string and other -client options by passing a ``ClientOptions`` object to the ``Connect()`` -method. - -To specify your connection URI, pass it to the ``ApplyURI()`` -method, which returns a new ``ClientOptions`` instance. To set any other -options, call the relevant helper method from the ``options`` package. - -To learn more about connection options, see the -:ref:`Connection Options section `. To learn -more about creating a client, see the API documentation for `Client -<{+api+}/mongo#Client>`__ and `Connect() <{+api+}/mongo#Connect>`__. - -You can set the {+stable-api+} version as an option to avoid -breaking changes when you upgrade to a new server version. To -learn more about the {+stable-api+} feature, see the :ref:`{+stable-api+} page -`. - -The following code shows how you can create a client that uses an Atlas -connection string and the {+stable-api+} version, connect to MongoDB, and -verify that the connection is successful: - -.. _go-connection-example-code: - -.. literalinclude:: /includes/fundamentals/code-snippets/srv.go - :language: go - -.. tip:: - - Follow the :ref:`Quick Start guide ` - to retrieve your Atlas connection string. - -.. note:: - - To learn about connecting to Atlas Serverless, see the - :ref:`Serverless Instance Limitations page - ` to identify the minimum driver version - required. - --------------------------------- -Other Ways to Connect to MongoDB --------------------------------- - -If you are connecting to a single MongoDB server instance or replica set -that is not hosted on Atlas, see the following sections to find out how to -connect. - -Connect to a MongoDB Server on Your Local Machine -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. include:: /includes/localhost-connection.rst - -To test whether you can connect to your server, replace the connection -string with your localhost connection string in the preceding code example. - -Connect to a Replica Set -~~~~~~~~~~~~~~~~~~~~~~~~ - -A MongoDB replica set deployment is a group of connected instances that -store the same set of data. This configuration provides data -redundancy and high data availability. - -To connect to a replica set deployment, specify the hostname and port numbers -of each instance, separated by commas, and the replica set name as the value -of the ``replicaSet`` parameter in the connection string. In the following -example, the hostnames are ``host1``, ``host2``, and ``host3``, and the -port numbers are all ``27017``. The replica set name is ``myRS``. - -.. code-block:: none - - mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRS - -When connecting to a replica set, the driver takes the following actions by default: - -- Discovers all replica set members when given the address of any one member. -- Dispatches operations to the appropriate member, such as instructions - to write against the **primary**. - -.. tip:: - - You can specify just one host to connect to a replica set. - However, to ensure connectivity when the specified host - is unavailable, provide the full list of hosts. - -Direct Connection -````````````````` - -To force operations on the host designated in the connection URI, -specify the ``directConnection`` option. Direct connections exhibit the -following behavior: - -- They don't support SRV strings. -- They fail on writes when the specified host is not the **primary**. -- They require you to specify a :manual:`secondary read preference - ` when the - specified host isn't the **primary** node. - -.. note:: Replica Set in Docker - - .. sharedinclude:: dbx/docker-replica-set.rst +For more information about authenticating with a MongoDB instance, see the +:ref:`golang-authentication` section. \ No newline at end of file diff --git a/source/connect/mongoclient.txt b/source/connect/mongoclient.txt index 226818c7..61a880fe 100644 --- a/source/connect/mongoclient.txt +++ b/source/connect/mongoclient.txt @@ -10,5 +10,146 @@ Create a MongoClient :depth: 2 :class: singlecol +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: connection string, URI, Atlas, code example -.. TODO \ No newline at end of file +Overview +-------- + +In this guide, you can learn how to connect to a `MongoDB Atlas deployment +`__, a MongoDB instance, or a replica set +using the {+driver-short+}. + +To connect to a MongoDB deployment, you need the following two things: + +- **Connection URI**, also known as a *connection string*, which tells the {+driver-short+} + which MongoDB deployment to connect to. + +- **MongoClient** object, which creates the connection to and performs operations + on the MongoDB deployment. + +You can use ``options.Client()`` to customize the way the {+driver-short+} +behaves while connected to MongoDB. + +Connection URI +-------------- + +A standard connection string includes the following components: + +.. list-table:: + :widths: 20 80 + :header-rows: 1 + + * - Component + - Description + + * - ``mongodb://`` + + - Required. A prefix that identifies this as a string in the + standard connection format. + + * - ``username:password`` + + - Optional. Authentication credentials. If you include these, the client + authenticates the user against the database specified in ``authSource``. + For more information about the ``authSource`` connection option, + see the :ref:`golang-connection-troubleshooting` guide. + + * - ``host[:port]`` + + - Required. The host and optional port number where MongoDB is running. If you don't + include the port number, the driver uses the default port, ``27017``. + + * - ``/defaultauthdb`` + + - Optional. The authentication database to use if the + connection string includes ``username:password@`` + authentication credentials but not the ``authSource`` option. + When you call ``client.db()`` with no argument, this is the database that is used. If you don't include + this component, the client authenticates the user against the ``admin`` database. + + * - ``?`` + + - Optional. A query string that specifies connection-specific + options as ``=`` pairs. See + :ref:`golang-connection-options` for a full description of + these options. + +.. tip:: + + To retrieve a connection string for an Atlas deployment, follow the + :ref:`Quick Start guide `. + +For more information about creating a connection string, see :manual:`Connection +Strings ` in the MongoDB Server documentation. + +Create a Client to Connect to MongoDB Atlas +------------------------------------------- + +To connect to MongoDB, you must create a client. A client manages your +connections and runs database commands. + +You can create a client that uses your connection string and other client +options by passing a ``ClientOptions`` object to the ``Connect()`` method. + +To specify your connection URI, pass it to the ``ApplyURI()`` method, which +returns a new ``ClientOptions`` instance. To set any other options, call the +relevant helper method from the options package. + +.. tip:: Reuse Your Client with Connection Pools + + We recommend that you reuse your client across sessions and operations by + using a connection pool. You can use the same ``Client`` instance to perform + multiple tasks, instead of creating a new one each time. The ``Client`` type + is safe for concurrent use by multiple `goroutines + `__. To learn more about how connection + pools work in the driver, see the :ref:`golang-connection-pools` guide. + +To learn more about connection options, see the :ref:`Connection Options +` section. To learn more about creating a client, see +the API documentation for `Client <{+api+}/mongo#Client>`__ and `Connect() +<{+api+}/mongo#Connect>`__. + +You can set the {+stable-api+} version as an option to avoid breaking changes +when you upgrade to a new server version. To learn more about the {+stable-api+} +feature, see the :ref:`{+stable-api+} page `. + +.. _go-connection-example-code: + +Example +~~~~~~~ + +The following code shows how you can create a client that uses an Atlas +connection string and the {+stable-api+} version, connects to MongoDB, and verifies +that the connection is successful: + +.. literalinclude:: /includes/fundamentals/code-snippets/srv.go + :language: go + :copyable: + :dedent: + +Additional Resources +-------------------- + +For more information about the concepts in this guide, see the following +documentation: + +- :manual:`Connection Strings ` in the Server + manual +- :manual:`Connection String Options ` in the + Server manual +- :atlas:`Driver Connection ` guide in the Atlas documentation + and select :guilabel:`Go` from the language dropdown + +API Documentation +~~~~~~~~~~~~~~~~~ + +To learn more about the methods and types discussed in this guide, see the +following API Documentation: + +- `Client <{+api+}/mongo#Client>`__ +- `ClientOptions <{+api+}/mongo/options#ClientOptions>`__ diff --git a/source/includes/fundamentals/code-snippets/srv.go b/source/includes/fundamentals/code-snippets/srv.go index b2df50aa..d59478c6 100644 --- a/source/includes/fundamentals/code-snippets/srv.go +++ b/source/includes/fundamentals/code-snippets/srv.go @@ -18,11 +18,13 @@ func main() { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/") } - // Use the SetServerAPIOptions() method to set the Stable API version to 1 + // Uses the SetServerAPIOptions() method to set the Stable API version to 1 serverAPI := options.ServerAPI(options.ServerAPIVersion1) + + // Defines the options for the MongoDB client opts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPI) - // Create a new client and connect to the server + // Creates a new client and connects to the server client, err := mongo.Connect(opts) if err != nil { @@ -34,7 +36,7 @@ func main() { } }() - // Send a ping to confirm a successful connection + // Sends a ping to confirm a successful connection var result bson.M if err := client.Database("admin").RunCommand(context.TODO(), bson.D{{"ping", 1}}).Decode(&result); err != nil { panic(err) diff --git a/source/includes/localhost-connection.rst b/source/includes/localhost-connection.rst index c18be21a..1f536403 100644 --- a/source/includes/localhost-connection.rst +++ b/source/includes/localhost-connection.rst @@ -11,9 +11,9 @@ purposes, complete the following steps: .. important:: - Always secure your MongoDB server from malicious attacks. See our - :manual:`Security Checklist ` for a - list of security recommendations. + Always secure your MongoDB server from malicious attacks. See the + :manual:`Security Checklist ` in the + Server manual for a list of security recommendations. After you successfully start your MongoDB server, specify your connection string in your driver connection code. @@ -22,5 +22,6 @@ If your MongoDB Server is running locally, you can use the connection string ``"mongodb://localhost:"`` where ```` is the port number you configured your server to listen for incoming connections. -If you want to specify a different hostname or IP address, see our Server -Manual entry on :manual:`Connection Strings `. \ No newline at end of file +For more information on how to specify a different hostname or IP address, see +:manual:`Connection Strings ` in the Server +manual. \ No newline at end of file