Introduction
Connecting to your database server is usually one of the first tasks you need to accomplish when designing and configuring database-backed applications. While there are many methods of providing the address, listening port, credentials, and other details to applications, connection URIs, sometimes called connection strings or connection URLs, are one of the most powerful and flexible ways of specifying complex configuration in a compact format.
In this guide, we'll talk about how to format a connection URI with your MongoDB database information and authentication details. Connection URIs are divided into sections, so we'll cover each part as we go along.
Percent encoding values
Before we begin, we should mention that MongoDB connection URIs expect percent-encoded values. This means that any characters that have a special meaning within the URL must be converted to their percent-encoded counterparts to ensure that libraries and applications can interpret them correctly.
Characters you should percent-encode include:
:
:%3A
/
:%2F
?
:%3F
#
:%23
[
:%5B
]
:%5D
@
:%40
These have special meaning within the connection URI.
So if your password is...:
pe@ce&lo\/3
...you'll want to specify it within the connection URI as:
pe%40ce&lo\%2F3
If you are unsure about whether a character should be percent-encoded, it's usually best to encode it anyways. For example, if you are unsure if the \
character is reserved, you can use it's percent-encoded equivalent, %5C
, to be safe:
pe%40ce%26lo%5C%2F3
Keep this in mind as you build your connection URIs.
A quick overview
Before we get into the details, we can look at the spec for a MongoDB connection URI:
mongodb://[username:password@]host[:port][,...hostN[:port]][/[database][?parameter_list]]\________/\__________________/\___________________________/\__________/\________________/| | | | ||- schema |- auth credentials | | |- parameter list| || |- default authentication database||- host specifier
The parts in square brackets indicate optional parts. You may have noticed that most parts of the URI are optional. It might also be apparent that there are many pieces of information you can encode in the URI.
A quick description of each of the individual components:
mongodb://
: The schema identifier used to identify the string as a MongoDB connection URI.auth credentials
: An optional component of the URI that can be used to specify the user and password to connect as.username
: An optional username. If included, it should start after the second slash (/
) and continue until a colon (:
). Must be accompanied by apassword
if included.password
: An optional password. If included, it begins after a colon (:
) and continues until the at sign (@
). Must be accompanied by ausername
if included.
host specifier
: A required component used to specify one or more hostnames and ports to connect to.host
: An IP address, DNS name, or locally resolvable name of the server to connect to. The host continues until a colon (:
) (if a port is included), until a comma (,
) if more than one host is specified, or else until a slash (/
). At least one host must be provided.port
: An optional port specification to indicate which port MongoDB is listening to on the host. The port begins with a colon (:
) and continues until a comma (,
) if another host is provided or until the slash (/
) if not.
default authentication database
: The name of the database to authenticate to if a more specificauthSource
is not provided in the parameter list. If no database is specified here or withauthSource
, MongoDB will attempt to authenticate to the standardadmin
database.parameter list
: An optional list of additional parameters that can affect the connection behavior. The parameter list begins with a question mark (?
). If no default authentication database is provided, you must begin the parameter list with both the slash and question mark (/?
) after the last host definition.parameter pairs
: The parameter list is composed of key-value pairs. The key and value within each pair are separated by an equal sign (=
) and each pair is separated from the next by an ampersand (&
).
Here is an example of a MongoDB connection URI that incorporates all of these components:
mongodb://sally:sallyspassword@dbserver.example:5555/userdata?tls=true&connectionTimeout=5000^ ^ ^ ^ ^ ^ ^|- schema | |- password |- host | | |- parameter list| | ||- username | |- default authentication database||- port
Specifying the URI type
The item in a connection URI is usually the protocol specification or application type. Since the URI will be used to connect and authenticate to a MongoDB database, we need to use a signifier that signifies that to the applications and libraries we're using.
The MongoDB project only accepts mongodb
as valid URI schema designators. Therefore, you should always start your connection URI like this:
mongodb://
The schema designator will ensure that the information that follows is interpreted in the correct context.
Specifying a username and password
The next part of the URI is the user credentials. User credentials are optional, but typically required if you don't want to rely on defaults configured by either your application or the database.
To include user credentials, provide the username after the schema identifier, followed by a colon (:
), the password, and finally an at sign (@
):
mongodb://username:password@
User credentials are optional, but if included, you must provide both the username and password components.
Specifying where the server is listening
After the user credentials comes the host specifier which defines where the server is listening. One or more hosts can be defined within the host specifier, but since the host specifier is required, at least one host must be provided.
Each host definition consists of a host
and an optional port
. The host
can either be a locally resolvable host name, a name resolved by an external name system like DNS, or an IP address or other direct address. The port signifies the port number on the host where MongoDB is listening.
To specify that the application should attempt to connect to the default MongoDB port (27017) on the local computer, you can use:
mongodb://localhost
If you needed to include a username and password, that information would come first and be separated by the at sign:
mongodb://username:password@localhost
To specify a remote server running on a non-standard port, separate those details with a colon. For example, to connect to port 3333 on a host at 198.51.100.22
, you could use:
mongodb://username:password@198.51.100.22:3333
To define more than one host and port pair, separate the sets by commas (,
) to tell the application to try the latter servers if the first cannot be reached. For example, to extend the previous example to include a fallback server listening on port 5555 on 198.51.100.33
, you could use:
mongodb://username:password@198.51.100.22:3333,198.51.100.33:5555
Conforming clients and applications will try to first connect to the server listening at 198.51.100.22:3333
. If that fails, they will try to reach a MongoDB database listening on 198.51.100.33:5555
.
Providing the default authentication database
After the host specifier, the next piece of data is the default authentication database. While not true for all database management systems, with MongoDB, you must authenticate against a specific database when establishing a connection.
The database name begins with a forward slash (/
) and proceeds until either the end of the line or a question mark (?
). The default authentication database will be used if an authSource
option is not provided within the parameter list. If neither are provided, the client will authenticate against the admin
database.
To connect to a database called sales
hosted on a MongoDB server listening on 198.51.100.22:3333
, you could type:
mongodb://username:password@198.51.100.22:3333/sales
Specifying additional parameters
The last part of the connection URI is used to provide additional parameters for the connection. The list of parameters is introduced by a leading question mark (?
) and continues until the end of the line. If no default authentication database is provided, the trailing slash indicating the end of the host specification must directly precede the question mark (/?
).
Each parameter listed is defined as a key and value pair joined with an equals sign (=
). After the first parameter pair, each additional key-value pair is separated by an ampersand (&
).
For example, to specify that the client should apply a 10 second timeout for the connection we were previously defining, you could use:
mongodb://username:password@198.51.100.22:3333/sales?connectTimeoutMS=10000
If you wanted to provide additional parameters, you'd add them afterwards with an ampersand (&
) between each pair. For instance, we could additionally specify that we require SSL and that the specified hosts are members of a replica set we want to connect to:
mongodb://username:password@198.51.100.22:3333,198.51.100.33:5555/sales?connectTimeoutMS=10000&tls=true&replicaSet=someReplicaSet
The MongoDB documentation has a full list of parameters that you can read to learn more.
Conclusion
In this guide, we discussed what a MongoDB connection URI is, how to interpret the various components, and how to construct your own URIs given a set of connection information. Connection URIs encode all of the information required to connect to a given database within a single string. Because of this flexibility and due to their wide adoption, understanding how to parse and construct those strings can be pretty helpful.
If you are using Prisma to manage your MongoDB database, you need to set a connection URI within a 'datasource' block in your Prisma schema file. You must provide a connection URI for the 'url' field so that Prisma can connect to your database.