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

Create a MongoClient

On this page

  • Connection URI
  • MongoClientSettings

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

A connection URI, also known as a connection string, tells the driver how to connect to a MongoDB deployment and how to behave while connected.

A standard connection string includes the following pieces:

Piece
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 will authenticate the user against the database specified in authSource.

host[:port]

Required. The host and optional port number where MongoDB is running. If you don't include the port number, the driver will use 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 piece, the client will authenticate 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.

To use a connection URI, pass it as a string to the MongoClient constructor. In the following example, the driver uses a sample connection URI to connect to a MongoDB instance on port 27017 of localhost:

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);

Tip

Reuse Your Client

Because each MongoClient represents a pool of connections to the database, most applications require only a single instance of MongoClient, even across multiple requests. To learn more about how connection pools work in the driver, see the FAQ page.

See the MongoDB Manual for more information about creating a connection string.

You can use a MongoClientSettings object to configure the connection in code rather than in a connection URI. To use a MongoClientSettings object, create an instance of the class and pass it as an argument to the MongoClient constructor.

In the following example, the driver uses a MongoClientSettings object to connect to a MongoDB instance on port 27017 of localhost:

using MongoDB.Driver;
// Creates a MongoClientSettings object
var settings = new MongoClientSettings()
{
Scheme = ConnectionStringScheme.MongoDB,
Server = new MongoServerAddress("localhost", 27017)
};
// Creates a new client and connects to the server
var client = new MongoClient(settings);

Back

Connect