Docs Menu
Docs Home
/ / /
C#/.NET
/

Choose a Connection Target

On this page

  • Overview
  • Atlas
  • Local Deployments
  • Replica Sets
  • Connect to a Single Server
  • DNS Service Discovery
  • API Documentation

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

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 driver connection guide 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 MongoDB Server. To learn more about the Stable API feature, see the Stable API guide.

The following code shows how to use .NET/C# Driver to connect to an Atlas cluster. The code also uses the server_api option to specify a Stable API version.

using MongoDB.Driver;
using MongoDB.Bson;
// Replace the placeholder with your Atlas connection string
const string connectionUri = "<connection string>";
var settings = MongoClientSettings.FromConnectionString(connectionUri);
// Sets the ServerApi field of the settings object to Stable API version 1
settings.ServerApi = new ServerApi(ServerApiVersion.V1);
// Creates a new client and connects to the server
var client = new MongoClient(settings);
// Sends a ping to confirm a successful connection
try {
var result = client.GetDatabase("admin").RunCommand<BsonDocument>(new BsonDocument("ping", 1));
Console.WriteLine("Pinged your deployment. You successfully connected to MongoDB!");
} catch (Exception ex) { Console.WriteLine(ex);}

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 .NET/C# Driver to connect to a local MongoDB deployment:

using MongoDB.Driver;
// Sets the connection URI
const string connectionUri = "mongodb://localhost:27017";
// Creates a new client and connects to the server
var client = new MongoClient(connectionUri);

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 .NET/C# Driver to connect to a replica set that contains three hosts:

using MongoDB.Driver;
// Sets the connection URI than includes the list of hosts in the replica set
const string connectionUri = "mongodb://host1:27017,host2:27017,host3:27017";
// Creates a new client and connects to the server
var client = new MongoClient(connectionUri);

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 .NET/C# Driver 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:

using MongoDB.Driver;
// Sets the connection URI than includes the replica set name
const string connectionUri = "mongodb://host1:27017/?replicaSet=sampleRS";
// Creates a new client and connects to the server
var client = new MongoClient(connectionUri);

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 .NET/C# Driver evenly load balances operations across deployments that are reachable within the client's localThresholdMS value. To learn more about how the .NET/C# Driver load balances operations across multiple MongoDB deployments, see the Customize 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.

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 MongoClientSettings or Connection String tab to see the corresponding code.

using MongoDB.Driver;
var settings = MongoClientSettings.FromConnectionString("mongodb://host1:27017");
settings.DirectConnection = true;
var client = new MongoClient(settings);
using MongoDB.Driver;
const string connectionUri = "mongodb://host1:27017/?directConnection=true";
var client = new MongoClient(connectionUri);

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 .NET/C# Driver 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:

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

To learn more about the SRV connection format, see the SRV Connection Format entry in the MongoDB Server manual.

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

Back

Create a MongoClient