Connection String in MongoDB (with examples)

For apps to connect to a database server, they must use a connection string, which is an expression that contains all of the parameters needed. Connection strings provide the server instance, database name, authentication details, and other parameters for interacting with the database server.

Formats for connection strings

Either of the given methods will set up a MongoDB connection string. The DNS Seed List Connection Format or the Standard Connection String Format.

The standard format for connecting strings

There are three basic types of MongoDB deployments: standalone, replica set, and sharded cluster, all of which are described here.

This is the typical way to join URIs.

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

Examples:

Standalone
mongodb://mongodb0.example.com:27017
Standalone that enforces access control:
mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017/?authSource=admin
Replica set
mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myRepl
Replica set that enforces access control:
mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?authSource=admin&replicaSet=myRepl
Sharded cluster
mongodb://mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017
Sharded cluster that enforces access control:
mongodb://myDBReader:D1fficultP%40ssw0rd@mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017/?authSource=admin

Components of a connection string

Components of the standard URI connection string:

  1. mongodb:// – A necessary prefix indicating a standard connection string.
  2. username:password@ – Authentication credentials are optional. If the authSource is given, the client will try to authenticate the user. Without specifying an authSource, the client will verify the user against the defaultauthdb. Additionally, the admin database is used if the defaultauthdb is not given.
  3. host[:port] – The host (and optionally the port number) on which the mongod instance is operating (or mongos instance in the case of a sharded cluster). You can indicate a hostname, an IP address, or a socket in a UNIX domain. Indicate the number of hosts required for your rollout topology:
    In the case of a single mongod instance, give the hostname of the mongod instance.
    Provide the hostname(s) of the mongod instance(s) specified in the replica set settings for a replica set.
    Indicate the mongos instance’s hostname(s) (s) for a sharded cluster. Without specifying a port number, the generic port 27017 is utilized.
  4. /defaultauthdb – Optional. If the connection string contains username:password@ credentials, but the authSource option is not supplied, the authentication database is used. The client uses the admin database to authenticate the user if both authSource and defaultauthdb are not given.
  5. ?<options> – Optional. Connection-specific parameters are specified in name>=value> pairs in the query string. The list of available choices may be seen in the Connection String Options section. Slash (/) must be included between the host and question mark (?) to begin the options string if no database is specified in the connection string.

Connection Format for the DNS Seed List

There is also a DNS-constructed seed list for MongoDB connections. Using DNS to build the list of accessible servers offers more deployment flexibility and the ability to switch servers in cycles without re-configuring clients.

Use the mongodb+srv prefix instead of the regular MongoDB connection string prefix to use the DNS seed list. To tell the user that the hostname following is a DNS SRV record, use the +srv prefix. Afterward, the mongosh or driver will query the domain name system (DNS) to discover which hosts are executing the mongod instances.

Note: The tls (or the corresponding ssl) option is set to true if the +srv connection string variable is used. By explicitly specifying the tls option to false in the query string, you may override this behavior and use tls=false instead.

DNS seed list connection strings often look like the following example:

mongodb+srv://server.example.com/

The DNS setup can look like this:

Record                            TTL   Class    Priority Weight Port  Target

_mongodb._tcp.server.example.com. 86400 IN SRV   0        5      27317 mongodb1.example.com.

_mongodb._tcp.server.example.com. 86400 IN SRV   0        5      27017 mongodb2.example.com.

Connecting with members of the seed list gives clients access to a directory of other replica set members to establish a connection. The host may produce a server list different from the seed list since clients commonly utilize DNS aliases in their seed lists. Replica set members can only be accessed via their hostnames; therefore, if this occurs, users will use the hostnames given by the replication rather than those stated in the seed list.

Note: The SRV records supplied by the specified hostname must have the same parent domain (example.com) as the hostname itself. You will not be permitted to connect if the parent domains and hostnames do not match.

Additionally, DNS seed list connection strings allow you to provide parameters as part of a URL in the same way that ordinary ones do. You may also use a TXT record to indicate the following settings when using a DNS seed list connection string:

authSource
replicaSet

Only one TXT record can be specified for each mongod instance. The client will return an error if the DNS has multiple TXT entries or if the TXT entry contains an attribute other than replicaSet or authSource.

The TXT record for server.example.com would look like this:

Record              TTL   Class    Text

server.example.com. 86400 IN TXT   "replicaSet=mySet&authSource=authDB"

This connection string is generated from the DNS SRV entries as well as the TXT record settings as follows:

mongodb://mongodb1.example.com:27317,mongodb2.example.com:27017/?replicaSet=mySet&authSource=authDB

A TXT record’s choices can be overridden by supplying the URL’s query string parameter. The query string in the following scenario overrides the authSource option set in the DNS entry’s TXT record.

mongodb+srv://server.example.com/?connectTimeoutMS=300000&authSource=aDifferentAuthDB

Using the authSource override, the typical connection string would look like this:

mongodb://mongodb1.example.com:27317,mongodb2.example.com:27017/?connectTimeoutMS=300000&replicaSet=mySet&authSource=aDifferentAuthDB

Note: If the hostname specified in the connection string does not have any DNS records associated with it, the mongodb+srv parameter will fail. As a last note, when using the +srv connection string modification, the option to utilize TLS (or the equivalent SSL security) is set to true for the connection. By explicitly specifying the tls option to false in the query string, you may override this behavior and use tls=false instead.

Get your MongoDB connection string

You’ll need a URI string to connect to MongoDB. If you link to a MongoDB deployment using the mongo shell, Compass, or the MongoDB drivers, you will be asked for the URI (Uniform Resource Identifier).

It is assumed that you have already set up authentication in MongoDB and generated a username and password for read and write rights to a MongoDB database when using the provided URI string.

In this case, you may use the login and password you created for the readWriteAnyDatabase role as well as the admin database name in your connection string to connect to MongoDB.

Options for the Connection String

This section explains the various ways you may connect to the Internet.

  1. In the form of a name=value pair, connection options are available.
  2. When utilizing a driver, the option name is case-insensitive.
  3. The option name is case-insensitive when using mongosh or the traditional mongo shell (version 4.2 or later).
  4. The option name is case-sensitive when using a version 4.0 or earlier legacy mongo shell.
  5. The case is never an issue when displaying the value.

The ampersand (&) letter can separate choices, such as name1=value1&name2=value2. ReplicaSet and connectTimeoutMS parameters are included in the following connection:

mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000

Note: Drivers now accept semi-colons (;) as option separators to preserve compatibility with older software.

Connection Strings Examples

You’ll find URI examples for popular connection points in the examples below.

Run the Database Server locally

The default port of a local database server may be used to establish a connection with the following command:

mongodb://localhost
Administrative Database

To log in to the admin database as foss with the password fosslinux, the following commands must be followed:

mongodb://foss:fosslinux@localhost
A database of records

Connecting and logging in to the records database using the password fosslinux as a system administrator.

mongodb://foss:fosslinux@localhost/records
Domain Sockets in UNIX

When attaching to a UNIX domain socket, use a URL encrypted connection string.

MongoDB links to a UNIX domain endpoint with the following path:

mongodb://%2Ftmp%2Fmongodb-27017.sock

Note: all drivers do not support UNIX domain sockets. To learn more about your driver, go to the Driver documentation section.

Replica set with users on distinct machines

Below is a connection to a two-member replica set on db1.example.net and db2.example.net:

mongodb://db1.example.net,db2.example.com/?replicaSet=test

Note: The mongod instance(s) provided in the replica set config must be specified for a replica set.

Replica Set with users on localhost

Ports 27017, 27018, and 27019 are used to establish a connection to a replica set operating on localhost:

mongodb://localhost,localhost:27018,localhost:27019/?replicaSet=test
Read Distribution Replica Set

Connecting to a three-member replica set and distributing reads to the secondary members entails the method listed below:

mongodb://example1.com,example2.com,example3.com/?replicaSet=test&readPreference=secondary
High Level Write Concern Replica Set

Connecting to a replica set containing write concern and a two-second timeout while waiting for replication across a majority of data-bearing voting members is accomplished using this configuration:

mongodb://example1.com,example2.com,example3.com/?replicaSet=test&w=majority&wtimeoutMS=2000
Shared Cluster

It is possible to connect to a multi-instance sharded cluster using the following:

mongodb://router1.example.com:27017,router2.example2.com:27017,router3.example3.com:27017/
MongoDB Atlas Cluster

The following establishes a connection to a MongoDB Atlas cluster using AWS IAM credentials for authentication:

mongosh 'mongodb+srv://<aws access key id>:<aws secret access key>@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS'

This example shows how to utilize the MONGODB-AWS authentication method and the $external authSource to connect to Atlas via AWS IAM credentials.

The AWS SESSION TOKEN authMechanismProperties value must be provided if you are utilizing an AWS session token, as follows:

mongosh 'mongodb+srv://<aws access key id>:<aws secret access key>@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<aws session token>'

Note: As long as the AWS access key ID or the Secret Access Key contains any of the following characters: (: / ? # [ ] @), you must use percent-encoding to encode them.

You may also use regular AWS IAM environment variables to specify these credentials on your platform. When using MONGODB-AWS authentication, mongosh checks and ascertains if the following environment variables are present:

  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEY
  • AWS_SESSION_TOKEN

A connection string does not need to include these credentials if configured.

In the bash shell, the following variables are set in the following example:

export AWS_ACCESS_KEY_ID='<aws access key id>'

export AWS_SECRET_ACCESS_KEY='<aws secret access key>'

export AWS_SESSION_TOKEN='<aws session token>'

The syntax for establishing environment variables will differ in other shells, so be aware of this. For further information, go to your platform’s documentation.

The following command will confirm whether or not certain environment variables have been set:

env | grep AWS

The following code exhibits how to establish a connection to a MongoDB Atlas cluster by using variables listed below:

mongosh 'mongodb+srv://cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS'

That’s all you need to know about connection strings in MongoDB. We hope you found the article guide helpful. If yes, please leave a remark in the comments section. Thanks for reading.

AD

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

SPONSOR AD
22,858FansLike
449FollowersFollow
16SubscribersSubscribe

More Articles Like This