A connection string consists of key-value pairs separated by semicolons. It specifies the MongoDB server, database, authentication credentials, and additional connection settings. This guide explains how to build connection strings for .NET applications that connect to MongoDB with dotConnect for MongoDB.
MongoDB connection strings
Connection string parameter names are case-insensitive. Most parameters also accept names without spaces, for example, UserId for User Id. This does not apply to Connection Timeout and the pooling parameters.
Some parameters have alternative names: Server and Data Source for Host, User and Uid for User Id, Pwd for Password, Auth Source and AuthSource for Auth Database, and Connect Timeout for Connection Timeout.
Parameters that you do not specify take their default values. If neither Host nor Url is set, the provider connects to localhost. The default port is 27017. The following example connects to a local MongoDB server:
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Host=localhost;" +
"Database=your_database;" +
"License Key=your_license_key");
conn.Open();
}
}
The values in the examples are placeholders. In real applications, store the password and other credentials in secure configuration instead of hard-coding them, and do not commit them to source control.
Authentication options
dotConnect for MongoDB authenticates with the credentials specified in the connection string or in a MongoDB connection URI. If neither User Id nor the URI specifies credentials, the provider connects without authentication: the connection opens, but the server rejects commands that require authentication.
| Option | When to use |
|---|---|
| No credentials | The server does not require authentication. Required parameters: none |
| User name and password | The server requires a user name and password. Required parameters: User Id, Password |
| Connection URI | You already have a MongoDB connection URI (mongodb:// or mongodb+srv://). The URI can include credentials and other connection settings, such as hosts, a replica set, and TLS options. Required parameter: Url |
No credentials
Specify the server and, optionally, the database, as in the example above.
User name and password
Specify User Id and Password. If the user account is defined in a database other than admin, set Auth Database to the name of that database.
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Host=localhost;" +
"Port=27017;" +
"User Id=your_username;" +
"Password=your_password;" +
"Database=your_database;" +
"Auth Database=admin;" +
"License Key=your_license_key");
conn.Open();
}
}
Connection URI
The Url parameter specifies a MongoDB connection URI. Separate connection string parameters take precedence over the URI: User Id, Password, Host, Port, and Additional Servers replace the corresponding parts of the URI, and the other parameters add options to it. Port and Additional Servers require Host: without it, an error is raised. If you specify User Id, also specify Password: the user name and password from the URI are not used.
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Url=mongodb://localhost:27017/your_database;" +
"User Id=your_username;" +
"Password=your_password;" +
"License Key=your_license_key");
conn.Open();
}
}
Special characters in the user name or password inside the URI, such as @, :, and /, must be percent-encoded.
Main connection properties
The following table lists the main parameters used in MongoDB connection strings.
| Name | Description |
|---|---|
| Host | The name or IP address of the MongoDB server. With Connection Format=DnsSeedList, the host name of the DNS SRV record. The default value is localhost when Url is not set |
| Port | The port the MongoDB server listens on. The default value is 27017 |
| Database | The database associated with the connection. With Sql Engine=true, its collections are available as tables |
| User Id | The MongoDB login account |
| Password | The password for the MongoDB login account |
| Auth Database | The database the user is defined in (authSource). If it is not set, MongoDB uses admin |
| Url | The MongoDB connection string URI (mongodb:// or mongodb+srv://) |
| Connection Format | Standard (mongodb://) or DnsSeedList (mongodb+srv://, the servers come from the DNS SRV record of Host). The default value is Standard |
| Additional Servers | Additional servers in a replica set or sharded cluster, in the host[:port],host[:port] format. Cannot be used with Connection Format=DnsSeedList |
| Replica Set | The name of the replica set (replicaSet) |
| Connection Options | Options of the MongoDB connection string URI added after the question mark, in the name=value&name=value format |
| Sql Engine | Enables the local SQL engine: commands are SQL statements, and collections are tables. Required for Entity Framework Core, Server Explorer, and SQL commands of the data adapter. When false, commands are MongoDB database commands in JSON, for example, {"find": ...} or {"insert": ...}. The default value is true |
| License Key | The dotConnect for MongoDB license key |
Replica set
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Host=your_host_1;" +
"Port=27017;" +
"Additional Servers=your_host_2:27017,your_host_3:27017;" +
"Replica Set=your_replica_set;" +
"User Id=your_username;" +
"Password=your_password;" +
"Database=your_database;" +
"License Key=your_license_key");
conn.Open();
}
}
DNS seed list (for example, MongoDB Atlas)
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Connection Format=DnsSeedList;" +
"Host=your_cluster_host;" +
"User Id=your_username;" +
"Password=your_password;" +
"Database=your_database;" +
"License Key=your_license_key");
conn.Open();
}
}
Native mode
With Sql Engine=false, the Reader Type parameter defines how documents are returned.
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Host=localhost;" +
"Database=your_database;" +
"Sql Engine=false;" +
"Reader Type=Document;" +
"License Key=your_license_key");
conn.Open();
}
}
MongoDBConnectionStringBuilder
The MongoDBConnectionStringBuilder class builds a connection string from typed properties and helps prevent errors in parameter names and in values that contain special characters. The property names are the parameter names without spaces, for example, Host, Port, UserId, Password, Database, AuthDatabase, Url, SslMode, Pooling, and LicenseKey.
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
MongoDBConnectionStringBuilder builder = new();
builder.Host = "localhost";
builder.Port = 27017;
builder.UserId = "your_username";
builder.Password = "your_password";
builder.Database = "your_database";
builder.LicenseKey = "your_license_key";
using MongoDBConnection conn = new(builder.ConnectionString);
conn.Open();
}
}
MongoDBConnection constructor
You can pass a connection string to the MongoDBConnection constructor:
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Host=localhost;" +
"Database=your_database;" +
"License Key=your_license_key");
conn.Open();
}
}
You can also create a connection with the default constructor and assign the connection string to its ConnectionString property:
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new();
conn.ConnectionString =
"Host=localhost;" +
"Port=27017;" +
"User Id=your_username;" +
"Password=your_password;" +
"Database=your_database;" +
"License Key=your_license_key";
conn.Open();
}
}
Connection pooling options
Connection pooling is enabled by default.
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Host=localhost;" +
"Database=your_database;" +
"Pooling=true;" +
"Min Pool Size=5;" +
"Max Pool Size=50;" +
"Connection Lifetime=60;" +
"License Key=your_license_key");
conn.Open();
}
}
| Name | Description |
|---|---|
| Pooling | If true, the connection is drawn from the appropriate pool or is created and added to the pool. The default value is true |
| Min Pool Size | The minimum number of connections allowed in the pool. The default value is 0 |
| Max Pool Size | The maximum number of connections allowed in the pool. Must be at least 1 and not less than Min Pool Size. The default value is 100 |
| Connection Lifetime | When a connection is returned to the pool, its creation time is compared with the current time. If the difference (in seconds) exceeds this value, the connection is closed. The default value is 0 (the connection always returns to the pool) |
Advanced connection string options
MongoDB-specific options
| Name | Description |
|---|---|
| Reader Type | Specifies how documents are returned when Sql Engine=false: Default (a column per field) or Document (the whole document as one value). The default value is Default |
| Native Library Path | The folder with the native libraries of the provider (libmongoc-1.0.dll, libbson-1.0.dll, and other native files shipped with it), either directly or in its Native\win-x86 or Native\win-x64, runtimes\win-x86\native or runtimes\win-x64\native, or x86 or x64 subfolder. It is searched before the folder of the provider assembly, the application folder, and the installation folder. The libraries are loaded once per process by the first connection, so a different path in a later connection has no effect |
| Describe Amount | The number of documents examined to determine the fields in a collection. Must be at least 1. The default value is 100 |
| Complex As String | With Sql Engine=true, returns embedded documents and arrays as single columns containing JSON instead of a column per nested field. The default value is false |
| Json Fields | With Sql Engine=true, the embedded documents and arrays returned as single columns containing JSON, as with Complex As String=true: collection.field items separated by semicolons |
| Allow Add Fields | With Sql Engine=true, INSERT and UPDATE statements may write a field that the collection or document does not have. When false, such writes raise an error. The default value is true |
| Create Collection On Insert | Specifies whether INSERT statements and MongoDBLoader create a collection automatically if it does not exist. When false, inserting data into a nonexistent collection raises an error. The default value is false |
| Schema Validation | Specifies how collections created with CREATE TABLE or the EF Core EnsureCreated method validate documents against the column schema: Off keeps the schema only to describe the columns, Warn logs documents that do not match it, and Error rejects them. The default value is Off |
| Transactions | Specifies how transactions are handled on a standalone server, which does not support them: IfSupported executes the commands without transactional atomicity, and Required raises an error. The default value is IfSupported |
| Decimal128 Mapping | The .NET type of Decimal128 values: String (the exact value), Decimal, or Double. The default value is String |
| DateTime Kind | The DateTime.Kind value assigned to dates read from the server: Utc (the time MongoDB stores) or Local. A DateTime value of the Unspecified kind is written as this kind. The default value is Utc |
| DateTimeOffset Format | How DateTimeOffset values are stored: DateTime (a BSON date, the offset is lost), Document ({DateTime, Ticks, Offset}, as in the official driver), Array ([Ticks, Offset in minutes]), or String. The default value is DateTime |
| Guid Format | How Guid values are stored: Uuid (BSON binary of subtype 4), Subtype3Rfc, Subtype3Guid, or Subtype3Reversed (subtype 3 in the byte order of RFC 4122, of System.Guid, or with each half reversed, as in Java), or String. The default value is Uuid |
| Connection Timeout | The maximum time, in seconds, to wait for a connection before raising a timeout error. 0 keeps the default of the native library. The default value is 30 |
| Socket Connect Timeout | The maximum time (in seconds) of one attempt to connect a socket to a server. It does not exceed Connection Timeout. 0 keeps the default of the native library. The default value is 10 |
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Host=localhost;" +
"Database=your_database;" +
"Connection Timeout=30;" +
"Socket Connect Timeout=10;" +
"License Key=your_license_key");
conn.Open();
}
}
Common options
| Name | Description |
|---|---|
| Persist Security Info | When false, security-sensitive values, such as the password, are removed from the ConnectionString property after the connection is opened. The parameter does not encrypt credentials. The default value is false |
| Enlist | If true, the provider automatically enlists the connection in the current transaction scope. The default value is true |
SSL/TLS connection strings
The TLS parameters take effect only with SSL Mode=Require. With Url, you can also specify the TLS options in the URI.
| Name | Description |
|---|---|
| SSL Mode | Whether the connection is encrypted with SSL/TLS: Disable or Require. The default value is Disable |
| Trust Server Certificate | With SSL Mode=Require, accepts the server certificate without validating its chain and host name. The default value is false |
| SSL CA Cert | The PEM file containing the certificate authority certificate used to validate the server certificate (tlsCAFile). Not supported on Windows: opening a connection with this parameter raises an error; import the CA certificate into the Windows certificate store instead |
| SSL Cert | The PEM file containing the client certificate and its private key (tlsCertificateKeyFile). On Windows, the key must be an unencrypted PKCS#1 RSA key |
| SSL Password | The password of the private key in SSL Cert (tlsCertificateKeyFilePassword). Not supported on Windows: opening a connection with this parameter raises an error |
Trust Server Certificate disables server certificate validation, which exposes the connection to man-in-the-middle attacks. Use it only in trusted test environments and keep certificate validation enabled in production.
Encrypted connection:
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Host=your_host;" +
"User Id=your_username;" +
"Password=your_password;" +
"Database=your_database;" +
"SSL Mode=Require;" +
"License Key=your_license_key");
conn.Open();
}
}
Connection with a client certificate:
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Host=your_host;" +
"User Id=your_username;" +
"Password=your_password;" +
"Database=your_database;" +
"SSL Mode=Require;" +
"SSL Cert=your_client_cert.pem;" +
"License Key=your_license_key");
conn.Open();
}
}
The connection string has no parameters for proxy servers, SSH tunneling, or HTTP tunneling.
Entity Framework Core connection strings
To use dotConnect for MongoDB with Entity Framework Core, call the UseMongoDB method of DbContextOptionsBuilder, usually in OnConfiguring. The method is provided by the Devart.Data.MongoDB.EFCore package. It takes a connection string and an optional action that configures MongoDB-specific options.
Entity Framework Core works through the SQL engine, so keep Sql Engine set to true (the default value).
using Devart.Data.MongoDB;
using Microsoft.EntityFrameworkCore;
class AppDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMongoDB(
"Host=localhost;" +
"Port=27017;" +
"User Id=your_username;" +
"Password=your_password;" +
"Database=your_database;" +
"License Key=your_license_key");
}
}
class Program
{
static void Main()
{
using AppDbContext db = new();
db.Database.OpenConnection();
}
}
Bulk loading connection strings
MongoDBLoader inserts multiple documents into a collection through an open MongoDBConnection. Its constructor takes the collection name and the connection. Call CreateColumns to get the structure of an existing collection, then Open to start loading. Use SetValue to assign field values and NextRow to add each document, and call Close to complete the operation:
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Host=localhost;" +
"Port=27017;" +
"User Id=your_username;" +
"Password=your_password;" +
"Database=your_database;" +
"License Key=your_license_key");
conn.Open();
MongoDBLoader loader = new("orders", conn);
loader.CreateColumns();
loader.Open();
loader.SetValue("id", 1);
loader.SetValue("name", "Laptop");
loader.NextRow();
loader.Close();
}
}
To load data into a new collection, set Create Collection On Insert=true in the connection string and declare the loader columns before calling Open:
using Devart.Data.MongoDB;
class Program
{
static void Main()
{
using MongoDBConnection conn = new(
"Host=localhost;" +
"Port=27017;" +
"User Id=your_username;" +
"Password=your_password;" +
"Database=your_database;" +
"Create Collection On Insert=true;" +
"License Key=your_license_key");
conn.Open();
MongoDBLoader loader = new("new_orders", conn);
loader.Columns.Add(new MongoDBLoaderColumn("id", MongoDBType.Integer));
loader.Columns.Add(new MongoDBLoaderColumn("name", MongoDBType.String));
loader.Open();
loader.SetValue("id", 1);
loader.SetValue("name", "Laptop");
loader.NextRow();
loader.Close();
}
}
With Sql Engine=false, the BatchSize property specifies the number of rows sent in each insert command (1,000 by default); with the SQL engine, rows are inserted one by one.
Conclusion
For most applications, a MongoDB connection string needs the server, the database, and the credentials. Use Url when you already have a MongoDB connection string URI, Additional Servers and Replica Set or Connection Format=DnsSeedList for clusters, and SSL Mode=Require for encrypted connections. Add pooling, data type mapping, and loading options only when your scenario requires them.
You can download the fully functional free trial of dotConnect for MongoDB and test it with your actual workload.