MongoDB connection

Connection strings

To access a MongoDB instance, you need a connection string. Depending on your MongoDB deployment which can be either a Standalone, a Replica Set or a Shared Cluster, the connection string must be set accordingly.

The generic format for a MongoDB connection string is:

mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]

Standalone deployment

For a local standalone instance that doesn't require users to identify themselves, use the following connection string:

mongodb://localhost:27017

If access control is enabled then the connection string should contain the user's username and password and optionally the database associated with the user's credentials. The latter can be set using the authSource options parameter.

mongodb://chsakell:myPassword@mongodb0.example.com:27017/?authSource=persons

The above connection string will try to authenticate user chsakell with password myPassword against the persons database.

MongoClient

The easiest way to connect to a MongoDB standalone instance via C# is to create an instance of MongoClientand pass the connection string to it's constructor:

// Create a mongodb client
var client = new MongoClient(DefaultConnectionString);

public static string DefaultConnectionString = 
  Program.Configuration.GetConnectionString("MongoDBConnection");

Last updated