Create a MongoClient
On this page
This guide shows you how to connect to a MongoDB instance or replica set deployment by using the .NET/C# Driver.
Connection URI
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 |
---|---|
| Required. A prefix that identifies this as a string in the standard connection format. |
| Optional. Authentication credentials. If you include these, the client will authenticate the user against the database specified in |
| 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, |
| Optional. The authentication database to use if the
connection string includes |
| Optional. A query string that specifies connection-specific
options as |
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.
MongoClientSettings
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);