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

Create a MongoClient

This guide shows you how to connect to a MongoDB instance or replica set deployment by using the .NET/C# Driver.

Connecting to a MongoDB deployment requires the following components:

  • Connection URI, also known as a connection string, which tells the .NET/C# Driver which MongoDB deployment to connect to.

  • MongoClient object, which creates and sustains the connection to the MongoDB deployment and lets you perform data operations.

You can also specify connection settings in either of these components to customize the way the .NET/C# Driver behaves while connected to MongoDB.

This guide shows you how to create a connection URI and use a MongoClient object to connect to MongoDB.

A standard connection URI includes the following components:

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 authentication settings, see Authentication Mechanisms.

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. If you don't include this component, the client authenticates the user against the admin database.

?<options>

Optional. A query string that specifies connection-specific options as <name>=<value> pairs. See Connection Options for a full description of these options.

For more information about creating a connection string, see Connection Strings in the MongoDB Server documentation.

To create a connection to MongoDB, pass a connection URI to the MongoClient constructor. In the following example, the driver uses a sample connection URI to connect to a MongoDB deployment running on port 27017 of localhost:

const string uri = "mongodb://localhost:27017/";
var client = new MongoClient(uri);

You can configure settings for the MongoClient object by passing a MongoClientSettings object to the constructor. The following example creates a MongoClient object and sets the UseTls property to true:

var connectionString = "mongodb://localhost:27017/"
var settings = MongoClientSettings.FromConnectionString(connectionString);
settings.UseTls = true;

To view a full list of the settings you can configure, see the Connection Options guide.

To learn more about creating a MongoClient object with the .NET/C# Driver, see the following API documentation:

Back

Connect

On this page