Docs Menu
Docs Home
/ / /
Laravel MongoDB
/ /

Connection Guide

On this page

  • Overview
  • Connection URI
  • Parts of a Connection URI
  • Laravel Database Connection Configuration
  • Connection Example
  • Other Ways to Connect to MongoDB
  • Connect to a MongoDB Server on Your Local Machine
  • Connect to a Replica Set

In this guide, you can learn how to connect your Laravel application to a MongoDB instance or replica set deployment by using Laravel MongoDB.

This guide includes the following sections:

  • Connection URI, which explains connection URIs and their constituent parts

  • Laravel Database Connection Configuration, which explains how to set up your MongoDB database connection for your Laravel app.

  • Connection Example, which provides examples that show how to connect to MongoDB by using an Atlas connection string.

  • Other Ways to Connect to MongoDB describes ways to connect to MongoDB deployments that are not hosted on Atlas.

A connection URI, also known as a connection string, specifies how the Laravel Integration connects to MongoDB and how to behave while connected.

The following figure explains each part of a sample connection URI:

Parts of a connection URI

In this connection URI, mongodb+srv is the protocol, which uses the DNS Seed List Connection Format for greater flexibility in your deployment and the ability to change the servers in rotation without reconfiguring clients.

If the machine that hosts your MongoDB deployment does not support this feature, use protocol for the Standard Connection String Format instead.

If you use a password-based authentication, the part of the connection string after the protocol contains your username and password. Replace the placeholder for user with your username and pass with your password. If you use an authentication mechanism that does not require a username and password, omit this part of the connection URI.

The part of the connection string after the credentials specifies your MongoDB instance's hostname or IP address and port. The preceding example uses sample.host as the hostname and 27017 as the port. Replace these values to point to your MongoDB instance.

The last part of the connection string specifies connection and authentication options. In the example, we set the following connection options and values:

  • maxPoolSize=20

  • w=majority

To learn more about connection options, see Connection Options.

The Laravel Integration lets you configure your MongoDB database connection in the config/database.php Laravel application file. You can specify the following connection details in this file:

  • default, which specifies the database connection to use when unspecified

  • connections, which contains database connection information to access one or more databases from your application

You can use the following code in the configuration file to set the default connection to a corresponding mongodb entry in the connections array:

'default' => 'mongodb',

For a MongoDB database connection, you can specify the following details:

Setting
Description
driver
Specifies the database driver to use for the connection.
dsn
The data source name (DSN) that specifies the MongoDB connection URI.
host
Specifies the network address and port of one or more MongoDB nodes in a deployment. You can use this setting instead of the dsn setting.
To specify a single host, pass the hostname and port as a string as shown in the following example:
'host' => 'myhost.example.com:27017',
To specify multiple hosts, pass them in an array as shown in the following example::
'host' => ['node1.example.com:27017', 'node2.example.com:27017', 'node3.example.com:27017'],
This option does not accept hosts that use the DNS seedlist connection format.
database
Specifies the name of the MongoDB database to read and write to.
username
Specifies your database user's username credential to authenticate with MongoDB.
password
Specifies your database user's password credential to authenticate with MongoDB.
options
Specifies connection options to pass to MongoDB that determine the connection behavior. To learn more about connection options, see Connection and Authentication Options.
driver_options
Specifies options specific to pass to the MongoDB PHP Library that determine the driver behavior for that connection. To learn more about driver options, see Driver Connection Options.

Note

You can specify the following settings in the dsn configuration as parameters in your MongoDB connection string instead of as array items:

  • host

  • username

  • password

  • options and driver_options, which are specified by the option name

The following example shows how you can specify your MongoDB connection details in the connections array item:

Example config/database.php MongoDB connection configuration
'connections' => [
'mongodb' => [
'driver' => 'mongodb',
'dsn' => 'mongodb+srv//myUser:myPass123@sample.host:27017/',
'database' => 'sample_mflix',
'options' => [
'maxPoolSize' => 20,
'w' => 'majority',
],
'driver_options' => [
'serverApi' => 1,
],
],
// ...
],

The following sections provide common ways of specifying MongoDB connections.

This section shows how to configure your Laravel application's DSN by using a MongoDB Atlas connection string.

To add your MongoDB DSN to your Laravel application, make the following changes:

  • Add the DSN as an environment variable in your project's .env environment configuration file. Set the variable value to your Atlas connection string.

  • Add a connection entry for your MongoDB connection in the connections array of your config/database.php configuration file. Set the dsn value of the connection entry to reference the environment variable that contains your DSN.

The following examples show how to specify "mongodb+srv://myUser:myPass123@mongodb0.example.com/" as the connection string in the relevant configuration files:

Sample .env environment configuration
DB_URI="mongodb+srv://myUser:myPass123@mongodb0.example.com/"
Sample config/database.php connection entry
'connections' => [
'mongodb' => [
'dsn' => env('DB_URI'), // uses the value of the DB_URI environment variable
'driver' => 'mongodb',
'database' => 'sample_mflix',
// ...
],
// ...
]

Tip

To retrieve your Atlas connection string, follow the Create a Connection String step of the Quick Start tutorial.

The following sections show you how to connect to a single MongoDB server instance or a replica set not hosted on MongoDB Atlas.

This section shows an example connection string you can use when running a Laravel application and MongoDB server from the same machine, such as your local development environment.

To connect your application to a MongoDB instance hosted on the same machine, you must complete the following tasks:

  • Download, install, and run the MongoDB server.

  • Obtain the IP address and port on which your MongoDB server is running. If you use the default settings of a local installation of MongoDB server, the IP address is 127.0.0.1, and the port is 27017.

  • Set up your config/database.php connection to reference the environment variable DB_URI for the value of the dsn, as shown in the Connection Example section.

The following example shows a sample connection string that you can add to the .env file if your application connects to a MongoDB server running on the default IP address and port:

Sample .env environment configuration to connect to a local MongoDB server.
DB_URI="mongodb://127.0.0.1:27017/";

To learn how to download and install MongoDB server, see Install MongoDB Community Edition in the Server manual.

A MongoDB replica set deployment is a group of connected instances, or nodes, where the nodes store the same data set. This configuration of instances provides data redundancy and high data availability.

To connect to a replica set deployment, specify each node's hostname and port number, separated by commas, and the replica set name as the value of the replicaSet parameter in the connection string.

This example, which shows the connection string you can add to your Laravel application's .env file to connect to a replica set, uses the following sample values:

  • host1, host2, and host3 as the hostnames of the MongoDB nodes

  • 27017 as the port on which MongoDB runs on those hosts

  • myRS as the configured name of the replica set

  • myUser and myPass123 as the credentials of a database user

DB_URI="mongodb://myUser:myPass123@host1:27017,host2:27017,host3:27017/?replicaSet=myRS"

When connecting to a replica set, the library that the Laravel Integration uses to manage connections with MongoDB performs the following actions unless otherwise specified:

  • Discovers all replica set members when given the address of any one member.

  • Sends operations to the appropriate member, such as instructions to write against the primary node. To learn more about the replica set primary, see Replica Set Primary in the Server manual.

Tip

You are required to specify only one host to connect to a replica set. However, to ensure connectivity when the selected host is unavailable, provide the full list of hosts.

To learn more about setting up a MongoDB replica set, see Deploy a Replica Set in the Server manual.

To force operations to run on a specific node in a MongoDB replica set, specify the connection information for the node in the connection string and the directConnection parameter with a true value.

Direct connections include the following limitations:

  • DNS seed list connection format connection strings cannot be used.

  • Write operations fail when the specified host is not the primary.

  • When the host is not the primary, you must specify the secondary read preference in your connection options. To learn more about this limitation, see the secondary read preference entry in the Server manual.

The following example shows the connection string you can add to your Laravel application's .env file to establish a direct connection to a secondary node in a MongoDB replica set. The example uses the following sample values:

  • host2 as the hostname of the secondary node

  • 27017 as the port on which the MongoDB node listens on

Sample .env environment configuration to enable a direct connection
DB_URI="mongodb://host2:27017/?directConnection=true&readPreference=secondary"

Back

Connections