Connecting from Code
The CData ADO.NET Provider for MongoDB implements a standard DbConnection object in MongoDBConnection. You can also use the MongoDBConnectionStringBuilder to programmatically build, parse, and rebuild connection strings.
Creating Connection Objects
See Establishing a Connection for guides to defining the connection string and authenticating. Below is a typical invocation to create MongoDBConnection objects.
C#
using (MongoDBConnection connection =
new MongoDBConnection("Server=127.0.0.1;Port=27017;Database=test;User=test;Password=test;"))
{
connection.Open();
}
VB.NET
Using connection As New MongoDBConnection("Server=127.0.0.1;Port=27017;Database=test;User=test;Password=test;")
connection.Open
End Using
Using MongoDBConnectionStringBuilder
The following code example shows how to use an ADO.NET connection string builder to parse a connection string.
C#
MongoDBConnectionStringBuilder builder =
new MongoDBConnectionStringBuilder("Server=127.0.0.1;Port=27017;Database=test;User=test;Password=test;");
//Pass the connection string builder an existing connection string, and you can get and set any of the elements as strongly typed properties.
builder.ConnectionString = "Server=127.0.0.1;Port=27017;Database=test;User=test;Password=test;";
//Now that the connection string has been parsed,
// you can work with individual items:
builder.MyString = "new property";
builder.MyBoolean = true;
// You can refer to connection keys using strings,
// as well.
builder["Logfile"] = "test.log";
builder["Verbosity"] = 5;
VB.NET
Dim builder As MongoDBConnectionStringBuilder = New MongoDBConnectionStringBuilder("Server=127.0.0.1;Port=27017;Database=test;User=test;Password=test;")
'Pass the connection string builder an existing connection string, and you can get and set any of the elements using strongly typed properties.
builder.ConnectionString = Server=127.0.0.1;Port=27017;Database=test;User=test;Password=test;"
'Now that the connection string has been parsed,
' you can work with individual items:
builder.MyString = "new property"
builder.MyBoolean = True
' You can refer to connection keys using strings,
' as well.
builder("Logfile") = "test.log"
builder("Verbosity") = 5