dotConnect for MongoDB Documentation
On this page
    Connecting to MongoDB
    On this page

    This tutorial describes how to connect to MongoDB.

    Requirements

    To connect to MongoDB, you need to have access to a MongoDB server (a standalone server, a replica set, a sharded cluster, or a cloud cluster), dotConnect for MongoDB installed, and the IDE running. You also need to know the connection parameters described below.

    Connection Parameters

    To establish a connection to the server, you have to provide the connection parameters to dotConnect for MongoDB. The MongoDBConnection component uses them to connect to MongoDB. The parameters are represented as a connection string. You can compose the connection string manually or have dotConnect for MongoDB construct it for you.

    No connection string parameter is mandatory. Host is localhost by default, and User Id and Password are needed only if authentication is enabled on the server. The following connection strings are typical examples:

    Host=localhost;Port=27017;Database=sample;User Id=user;Password=pwd;License Key=***
    Url=mongodb+srv://user:[email protected]/sample;License Key=***
    Host=db1;Additional Servers=db2:27017,db3:27017;Replica Set=rs0;Database=sample;License Key=***
    

    The following table describes the connection string parameters.

    ParameterDefault valueDescription
    Host (Data Source, Server)localhostSpecifies the server name.
    Port27017Specifies the port number for the connection.
    Database Specifies the database used by the connection. If empty, it is taken from Url.
    Url Specifies a MongoDB URI, mongodb:// or mongodb+srv://. Explicit parameters override its parts; other parameters add options.
    Connection FormatStandardSpecifies the URI format: Standard – mongodb://; DnsSeedList – mongodb+srv://, servers come from the DNS SRV record of Host.
    Additional Servers Specifies more servers of a replica set or a sharded cluster as host[:port],host[:port]. Can't be used with DnsSeedList.
    Replica Set Specifies the replica set name.
    Connection Options Specifies extra URI options, name=value&name=value. They take precedence over the parameters below.
    User Id Specifies the user name for authentication.
    Password Specifies the password of the user.
    Auth Database (Auth Source)adminSpecifies the database that holds the user.
    Persist Security InfofalseSpecifies whether security-sensitive information, such as the password, is kept in the connection string after the connection is opened.
    SSL ModeDisableSpecifies whether to use SSL: Disable or Require. The other SSL parameters apply only with Require.
    Trust Server CertificatefalseAccepts any server certificate and host name.
    SSL Cert Specifies the PEM file with the client certificate and key. On Windows, an unencrypted PKCS#1 RSA key.
    SSL CA Cert Specifies the file with the CA certificate. Not supported on Windows; the CA comes from the Windows certificate store.
    SSL Password Specifies the password of the client certificate key. Not supported on Windows.
    Connection Timeout30Sets the total time in seconds that Open() waits, including server selection.
    Socket Connect Timeout10Sets the time in seconds for one attempt to connect a socket, at most Connection Timeout. 0 means the driver default.
    PoolingtrueEnables connection pooling.
    Min Pool Size0Specifies the minimum number of connections kept in the pool.
    Max Pool Size100Specifies the maximum number of connections in the pool.
    Connection Lifetime0Specifies the time in seconds after which a connection returned to the pool is destroyed. 0 means no limit.
    TransactionsIfSupportedDefines the behavior on a standalone server, which has no transactions: IfSupported runs the commands at once; Required raises an error.
    EnlisttrueEnlists the connection in the current TransactionScope.
    License Key Specifies the license key. See Activation.
    Sql EnginetrueSelects the working mode: true – SQL over collections; false – MongoDB commands in JSON.
    Reader TypeDefaultSpecifies how the reader returns data in native mode only: Default – a column per field; Document – the whole document as one value.
    Describe Amount100Specifies the number of documents read to describe the fields of a collection.
    Complex As StringfalseReturns every embedded document or array as one JSON column in SQL mode.
    Json Fields Returns only the listed fields as JSON columns in SQL mode, collection.field;collection.field.
    Allow Add FieldstrueLets INSERT, UPDATE and MongoDBLoader write a field that the collection or the document doesn't have in SQL mode. false raises an error.
    Create Collection On InsertfalseCreates the target collection if it doesn't exist when an INSERT or MongoDBLoader writes to it, in both modes. false raises an error.
    Schema ValidationOffSpecifies how CREATE TABLE and EF Core EnsureCreated set the schema of a collection: Off keeps the column list without checking documents; Warn logs a warning on the server for a document that doesn't match; Error rejects such documents for every client.
    Decimal128 MappingStringSpecifies how Decimal128 values are mapped: String, Decimal or Double.
    DateTime KindUtcSpecifies the kind of read dates (Utc or Local). A DateTime of Unspecified kind is written as this kind.
    Guid FormatUuidSpecifies how Guid values are stored: Uuid (binary subtype 4), Subtype3Rfc, Subtype3Guid, Subtype3Reversed or String.
    DateTimeOffset FormatDateTimeSpecifies how DateTimeOffset values are stored: DateTime (the offset is lost), Document, Array or String.
    Native Library Path Specifies the folder with libmongoc-1.0.dll, libbson-1.0.dll, sqlite3.dll, and vcruntime140.dll, directly or in its Native\win-<arch>, runtimes\win-<arch>\native, or <arch> subfolder. Here <arch> is x86, x64, or arm64, depending on the process.

    Creating a Connection to MongoDB

    Design-time creation

    This procedure assumes that the IDE is running and a form is open in the designer.

    1. Open the Toolbox and find the MongoDBConnection component in the dotConnect for MongoDB category.
    2. Double-click the component. A new object appears on the designer under the form. If this is the first time you create a MongoDBConnection in this application, it is named mongoDBConnection1.
    3. Click the mongoDBConnection1 object and press F4 to open its properties.
    4. Enter the connection parameters in the corresponding properties: UserId, Password, Host, Port, and Database.
      As you assign values to these properties, the ConnectionString property is automatically updated to reflect your settings. Now it contains something like "Host=localhost;Port=27017;Database=sample;User Id=user;Password=pwd;".
    5. To configure other connection string parameters, click the ellipsis (...) in the ConnectionString property. In MongoDBConnection Editor, set the parameters on the Parameters tab, then click OK. For the description of these parameters, see the MongoDBConnection.ConnectionString topic.

    Run-time creation

    You can configure a connection at run time by setting its ConnectionString property. Note that you must add references to the Devart.Data.MongoDB.dll and Devart.Data.dll assemblies.

    mongoDBConnection1.ConnectionString = "Host=localhost;Port=27017;Database=sample;User Id=user;Password=pwd;";
    
    mongoDBConnection1.ConnectionString = "Host=localhost;Port=27017;Database=sample;User Id=user;Password=pwd;"
    

    Using a connection string builder

    If you decide to set up the connection by assigning values to several properties, consider using the MongoDBConnectionStringBuilder class. It provides a property for each connection string parameter, which lets you configure every aspect of the connection.

    MongoDBConnectionStringBuilder connectionStringBuilder = new MongoDBConnectionStringBuilder();
    
    connectionStringBuilder.Host = "localhost";
    connectionStringBuilder.Port = 27017;
    connectionStringBuilder.Database = "sample";
    connectionStringBuilder.UserId = "user";
    connectionStringBuilder.Password = "pwd";
    
    MongoDBConnection myConnection = new MongoDBConnection(connectionStringBuilder.ConnectionString);
    
    Dim connectionStringBuilder As MongoDBConnectionStringBuilder = New MongoDBConnectionStringBuilder
    
    connectionStringBuilder.Host = "localhost"
    connectionStringBuilder.Port = 27017
    connectionStringBuilder.Database = "sample"
    connectionStringBuilder.UserId = "user"
    connectionStringBuilder.Password = "pwd"
    
    Dim myConnection As MongoDBConnection = New MongoDBConnection(connectionStringBuilder.ConnectionString)

    In this example we used the MongoDBConnection constructor that accepts a connection string as an argument.

    For information on the parameters you can use in the connection string, see the description of the MongoDBConnection.ConnectionString property.

    Creating a connection in Server Explorer

    To create a Server Explorer connection:

    1. On the Server Explorer toolbar, click Connect to Database.
    2. In the Add Connection dialog, click Change.
    3. Under Data source, select MongoDB Database.
    4. Under Data provider, select dotConnect for MongoDB, then click Continue.
    5. Enter the Host (defaults to localhost) and the Port (defaults to 27017).
    6. Optional: To connect using a mongodb+srv:// address, select Use DNS seed list: the servers are then taken from the DNS SRV record of the host.
    7. If authentication is enabled on the server, enter the User and Password, and the Auth Database that holds the user (admin by default).
    8. Specify the Database to work with.
    9. In SSL Mode, select Disable or Require. With Require, you can also select Trust Server Certificate to accept any server certificate and host name.
    10. Click OK.
    Add Connection dialog with dotConnect for MongoDB connection settings

    After this, you can browse MongoDB objects in Server Explorer.

    MongoDB connection in Server Explorer

    Opening a Connection

    To open a connection, call the Open method.

    mongoDBConnection1.Open();
    
    mongoDBConnection1.Open()
    

    The mongoDBConnection1 object must have a valid connection string assigned earlier. When you call Open, dotConnect for MongoDB tries to find the host and connect to MongoDB. If any problem occurs, it raises an exception with a brief explanation of what is wrong. If no problem is encountered, dotConnect for MongoDB tries to establish the connection within the Connection Timeout interval. When the connection is established, the Open method returns and the State property changes to Open.

    To connect to the server at design time:

    1. Right-click the connection object in the designer and select Connect.
    2. In the Connect dialog, enter the connection parameters: Host, Port, User, Password, Database, Auth Database, and SSL Mode. To use a mongodb+srv:// address, select Use DNS seed list.
    3. Click Connect.

    Alternatively, set the State property to Open in the Properties dialog to establish a connection using the current connection string.

    Closing a Connection

    To close a connection, call its Close method or set its State property to Closed. At design time, right-click the connection object in the designer and select Disconnect.

    The following example summarizes the preceding information and shows how to create, set up, open, use, and then close a connection.

    MongoDBConnection myConn = new MongoDBConnection();
    myConn.ConnectionString = "Host=localhost;Port=27017;Database=sample;User Id=user;Password=pwd;";
    myConn.Open();
    MessageBox.Show(myConn.ServerVersion);
    myConn.Close();
    
    Dim myConn As MongoDBConnection = New MongoDBConnection()
    myConn.ConnectionString = "Host=localhost;Port=27017;Database=sample;User Id=user;Password=pwd;"
    myConn.Open()
    MessageBox.Show(myConn.ServerVersion)
    myConn.Close()
    

    The sample code connects to the server, shows its version (the version of the MongoDB server, for example "8.0.0"), and then closes the connection. This is a rare usage, because in real applications connections are used by other objects such as MongoDBCommand, MongoDBDataReader, and others. For more information, see the corresponding tutorials or the reference documentation.

    Modifying a Connection

    You can modify a connection by changing the properties of the MongoDBConnection object. Keep in mind that while some of the properties can be altered freely, most of them close the connection when a new value is assigned.