Skip to content

DOCSP-49054: Connection targets #589

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion source/connect/connection-options/server-selection.txt
Original file line number Diff line number Diff line change
Expand Up @@ -192,4 +192,4 @@ documentation:
- `ClusterConfigurator <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.ClusterConfigurator.html>`__
- `ServerSelectors <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Clusters.ServerSelectors.html>`__
- `IServerSelector <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Clusters.ServerSelectors.IServerSelector.html>`__
- `SelectServer() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Clusters.ServerSelectors.IServerSelector.SelectServers.html>`__
- `SelectServer() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Clusters.ServerSelectors.IServerSelector.SelectServers.html>`__
174 changes: 174 additions & 0 deletions source/connect/connection-targets.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
.. _csharp-connection-targets:

==========================
Choose a Connection Target
==========================

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: connection string, URI, server, settings, client, load balancing, srv, dns

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

Overview
--------

In this guide, you can learn how to use a connection string and ``MongoClient`` object
to connect to different types of MongoDB deployments.

Atlas
-----

To connect to a MongoDB deployment on Atlas, include the following elements
in your connection string:

- URL of your Atlas cluster
- MongoDB username
- MongoDB password

Then, pass your connection string to the ``MongoClient`` constructor.

.. tip::

Follow the :atlas:`Atlas driver connection guide </driver-connection?tck=docs_driver_python>`
to retrieve your connection string.

When you connect to Atlas, we recommend using the {+stable-api+} client option to avoid
breaking changes when Atlas upgrades to a new version of {+mdb-server+}.
To learn more about the {+stable-api+} feature, see the :ref:`<csharp-stable-api>` guide.

The following code shows how to use {+driver-short+} to connect to an Atlas cluster. The
code also uses the ``server_api`` option to specify a {+stable-api+} version.

.. literalinclude:: /includes/fundamentals/code-examples/connection/AtlasConnection.cs
:language: csharp
:start-after: // start atlas connection
:end-before: // end atlas connection

Local Deployments
-----------------

To connect to a local MongoDB deployment, use ``localhost`` as the hostname. By
default, the ``mongod`` process runs on port 27017, though you can customize this for
your deployment.

The following code shows how to use {+driver-short+} to connect to a local MongoDB
deployment:

.. literalinclude:: /includes/fundamentals/code-examples/connection/LocalConnection.cs
:language: csharp
:start-after: // start local connection
:end-before: // end local connection

Replica Sets
------------

To connect to a replica set, specify the hostnames (or IP addresses) and
port numbers of the replica set members in your connection string.

The following code shows how to use {+driver-short+} to connect to a replica set
that contains three hosts:

.. literalinclude:: /includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs
:language: csharp
:start-after: // start-replica-set-connection-list
:end-before: // end-replica-set-connection-list

If you aren't able to provide a full list of hosts in the replica set, you can
specify one or more of the hosts in the replica set and instruct {+driver-short+} to
perform automatic discovery to find the others. To instruct the driver to perform
automatic discovery, perform one of the following actions:

- Specify the name of the replica set as the value of the ``replicaSet`` parameter.
- Specify ``false`` as the value of the ``directConnection`` parameter. You can also omit
this parameter, as it defaults to ``false``.
- Specify more than one host in the replica set.

In the following example, the driver uses a sample connection URI to connect to the
MongoDB replica set ``sampleRS``, which is running on port ``27017`` of three different
hosts, including ``host1``:

.. literalinclude:: /includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs
:language: csharp
:start-after: // start-replica-set-connection-rs-name
:end-before: // end-replica-set-connection-rs-name

.. note:: Specifying the Replica Set Name

Although the driver can automatically discover replica set members without specifying
the hostnames of all members or the replica set name, we recommend specifying the
replica set name to avoid corner cases where the replica set will not initialize
correctly.

The {+driver-short+} evenly load balances operations across deployments that are reachable
within the client's ``localThresholdMS`` value. To learn more about how the {+driver-short+} load
balances operations across multiple MongoDB deployments, see the
:ref:`csharp-server-selection` guide.

.. note::

The ``MongoClient`` constructor is *non-blocking*.
When you connect to a replica set, the constructor returns immediately while the
client uses background threads to connect to the replica set.

If you construct a ``MongoClient`` and immediately print the string representation
of its ``nodes`` attribute, the list might be empty while the client connects to
the replica set members.

Connect to a Single Server
~~~~~~~~~~~~~~~~~~~~~~~~~~

To connect to a single server in a replica set rather than the entire replica set, specify
``false`` as the value of the ``directConnection`` connection option. You can do this in two ways: by passing
an argument to the ``MongoClient`` constructor or through a parameter in your connection string. Select the
:guilabel:`MongoClientSettings` or :guilabel:`Connection String` tab to see the corresponding code.

.. tabs::

.. tab:: MongoClientSettings
:tabid: settings

.. literalinclude:: /includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs
:language: csharp
:start-after: // start-replica-set-direct-connection-settings
:end-before: // end-replica-set-direct-connection-settings

.. tab:: Connection String
:tabid: connection-string

.. literalinclude:: /includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs
:language: csharp
:start-after: // start-replica-set-direct-connection-string
:end-before: // end-replica-set-direct-connection-string

DNS Service Discovery
---------------------

To use DNS service discovery to look up the DNS SRV record of the service you're connecting to,
specify the SRV connection format in your connection string. Additionally, if you enable
the SRV connection format, the {+driver-short+} automatically re-scans for new hosts without
having to change the client configuration.

The following code shows a connection string that uses the SRV connection format:

.. code-block:: csharp

var uri = "mongodb+srv://<hostname>"

To learn more about the SRV connection format, see the :manual:`SRV Connection Format </reference/connection-string/#std-label-connections-dns-seedlist>`
entry in the {+mdb-server+} manual.

API Documentation
-----------------

To learn more about the types discussed in this guide, see the following API documentation:

- `MongoClient <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClient.html>`__
- `MongoClientSettings <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoClientSettings.html>`__
57 changes: 0 additions & 57 deletions source/connect/mongoclient.txt
Original file line number Diff line number Diff line change
Expand Up @@ -98,60 +98,3 @@ MongoDB instance on port ``27017`` of ``localhost``:
:dedent:
:start-after: // start mongo client settings
:end-before: // end mongo client settings

Other Connection Targets
------------------------

Connect to Atlas
~~~~~~~~~~~~~~~~

To connect to a MongoDB deployment on Atlas, create a client. You can
create a client that uses your connection string and other
client options by passing a ``MongoClientSettings`` object to the ``MongoClient``
constructor.

To specify your connection URI, pass it to the ``FromConnectionString()``
method, which returns a new ``MongoClientSettings`` instance. To specify any other
client options, set the relevant fields of the ``MongoClientSettings`` object.

You can set the {+stable-api+} version as a client 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
<csharp-stable-api>`.

The following code shows how you can specify the connection string and
the {+stable-api+} client option when connecting to a MongoDB
deployment and verify that the connection is successful:

.. literalinclude:: /includes/fundamentals/code-examples/connection/AtlasConnection.cs
:language: csharp
:start-after: // start atlas connection
:end-before: // end atlas connection

.. tip::

Follow the :atlas:`Atlas driver connection guide </driver-connection?tck=docs_driver_nodejs>`
to retrieve your connection string.

Connect to a Replica Set
~~~~~~~~~~~~~~~~~~~~~~~~

To connect to a replica set deployment, specify the hostnames (or IP addresses) and
port numbers of the members of the replica set.

If you aren't able to provide a full list of hosts in the replica set, you can
specify one or more of the hosts in the replica set and instruct the driver to
perform automatic discovery in one of the following ways:

- Specify the name of the replica set as the value of the ``replicaSet`` parameter.
- Specify ``false`` as the value of the ``directConnection`` parameter.
- Specify more than one host in the replica set.

In the following example, the driver uses a sample connection URI to connect to the
MongoDB replica set ``sampleRS``, which is running on port ``27017`` of three different
hosts, including ``sample.host1``:

.. literalinclude:: /includes/fundamentals/code-examples/connection/ReplicaSetConnection.cs
:language: csharp
:start-after: // start replica set connection
:end-before: // end replica set connection
Original file line number Diff line number Diff line change
@@ -1,11 +1,37 @@
// Connects to a specific replica set by using a URI

// start replica set connection
// start-replica-set-connection-rs-name
using MongoDB.Driver;

// Sets the connection URI than includes the replica set name
const string connectionUri = "mongodb://sample.host1:27017/?replicaSet=sampleRS";
const string connectionUri = "mongodb://host1:27017/?replicaSet=sampleRS";

// Creates a new client and connects to the server
var client = new MongoClient(connectionUri);
// end replica set connection
// end-replica-set-connection-rs-name

// start-replica-set-connection-list
using MongoDB.Driver;

// Sets the connection URI than includes the list of hosts in the replica set
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you forgot to include the replica set name here?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe the comment here is incorrect! Can fix it.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sanych-sun Another question... If we don't specify the replica set name here, wouldn't it be considered a standalone cluster?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we do not specify the replicaset name, it should be automatically discovered. However it's recommended to include the replicaset into the connection string if possible, to avoid wrong initialization in some corner cases (for example if connection seed list contains several hosts which are connected to a different replicasets - then result of connecting might depends on the fact what server reply first.)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mcmorisi should we include this info in the text?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will add a note!

const string connectionUri = "mongodb://host1:27017,host2:27017,host3:27017";

// Creates a new client and connects to the server
var client = new MongoClient(connectionUri);
// end-replica-set-connection-list

// start-replica-set-direct-connection-string
using MongoDB.Driver;

const string connectionUri = "mongodb://host1:27017/?directConnection=true";
var client = new MongoClient(connectionUri);
// end-replica-set-direct-connection-string

// start-replica-set-direct-connection-settings
using MongoDB.Driver;

var settings = MongoClientSettings.FromConnectionString("mongodb://host1:27017");
settings.DirectConnection = true;
var client = new MongoClient(settings);
// end-replica-set-direct-connection-settings

Loading