Skip to content

DOCSP-35938: Connection Guide docs #2881

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Apr 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/fundamentals.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@ Fundamentals
:titlesonly:
:maxdepth: 1

/fundamentals/connection
/fundamentals/database-collection
/fundamentals/read-operations
/fundamentals/write-operations

Learn how to use the {+odm-long+} to perform the following tasks:

- :ref:`Manage Databases and Collections <laravel-db-coll>`
- :ref:`Configure Your MongoDB Connection <laravel-fundamentals-connection>`
- :ref:`Databases and Collections <laravel-db-coll>`
- :ref:`Read Operations <laravel-fundamentals-read-ops>`
- :ref:`Write Operations <laravel-fundamentals-write-ops>`

25 changes: 25 additions & 0 deletions docs/fundamentals/connection.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
.. _laravel-fundamentals-connection:

===========
Connections
===========

.. toctree::

/fundamentals/connection/connect-to-mongodb

.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol

Overview
--------

Learn how to set up a connection from your Laravel application to a MongoDB
deployment and specify the connection behavior by using {+odm-short+} in the
following sections:

- :ref:`laravel-connect-to-mongodb`

355 changes: 355 additions & 0 deletions docs/fundamentals/connection/connect-to-mongodb.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,355 @@
.. _laravel-connect-to-mongodb:

================
Connection Guide
================

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: code example, seedlist, dsn, data source name

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

Overview
--------

In this guide, you can learn how to connect your Laravel application to a
MongoDB instance or replica set deployment by using {+odm-short+}.

This guide includes the following sections:

- :ref:`Connection URI <laravel-connection-uri>`, which explains connection
URIs and their constituent parts
- :ref:`laravel-database-config`, which explains how to set up your MongoDB
database connection for your Laravel app.
- :ref:`Connection Example <laravel-atlas-connection-example>`, which provides
examples that show how to connect to MongoDB by using an Atlas connection
string.
- :ref:`laravel-other-ways-to-connect` describes ways to connect to MongoDB
deployments that are not hosted on Atlas.

.. _laravel-connection-uri:

Connection URI
--------------

A **connection URI**, also known as a connection string, specifies how
{+odm-short+} connects to MongoDB and how to behave while connected.

Parts of a Connection URI
~~~~~~~~~~~~~~~~~~~~~~~~~

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

.. figure:: /includes/figures/connection_uri_parts.png
:alt: Parts of a connection URI

In this connection URI, ``mongodb+srv`` is the protocol, which uses the
:manual:`DNS Seed List Connection Format </reference/connection-string/#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
:manual:`Standard Connection String Format </reference/connection-string/#std-label-connections-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``

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note:
This section will include a link to the Connection Options page once completed.

.. _laravel-database-config:

Laravel Database Connection Configuration
------------------------------------------

{+odm-short+} 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:

.. code-block:: php

'default' => 'mongodb',

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

.. list-table::
:header-rows: 1
:widths: 25 75

* - 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:

.. code-block:: php
:copyable: false

'host' => 'myhost.example.com:27017',

| To specify multiple hosts, pass them in an array as shown in the
following example::

.. code-block:: php
:copyable: false

'host' => ['node1.example.com:27017', 'node2.example.com:27017', 'node3.example.com:27017'],

.. note::

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.

* - ``driverOptions``
- Specifies options specific to pass to the MongoDB PHP Library driver
that determine the driver behavior for that connection.
Comment on lines +152 to +158
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

@ccho-mongodb ccho-mongodb Apr 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I will add links from options and driverOptions to the Connection Options page (which includes the link you provided) once merged as a cleanup task.


.. 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 ``driverOptions``, which are specified by the option name

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

.. code-block:: php
:caption: Example config/database.php MongoDB connection configuration

'connections' => [
'mongodb' => [
'driver' => 'mongodb',
'dsn' => 'mongodb+srv//myUser:[email protected]:27017/',
'database' => 'sample_mflix',
'options' => [
'maxPoolSize' => 20,
'w' => 'majority',
],
'driverOptions' => [
'serverApi' => 1,
],
],
// ...
],

The following sections provide common ways of specifying MongoDB connections.

.. _laravel-atlas-connection-example:

Connection Example
------------------

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:[email protected]/"``
as the connection string in the relevant configuration files:

.. code-block:: bash
:caption: Sample .env environment configuration

DB_URI="mongodb+srv://myUser:[email protected]/"

.. code-block:: php
:caption: Sample config/database.php connection entry
:emphasize-lines: 3

'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
:ref:`Create a Connection String <laravel-quick-start-connection-string>`
step of the Quick Start tutorial.

.. _laravel-other-ways-to-connect:

Other Ways to Connect to MongoDB
--------------------------------

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

.. _laravel-connect-localhost:

Connect to a MongoDB Server on Your Local Machine
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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
:ref:`laravel-atlas-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:

.. code-block:: php
:caption: 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
:manual:`Install MongoDB Community Edition </installation/#mongodb-installation-tutorials>`
in the {+server-docs-name+}.

.. _laravel-connect-replica-set:

Connect to a Replica Set
~~~~~~~~~~~~~~~~~~~~~~~~

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

.. code-block:: bash

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After testing on a local replica set, I can confirm that the replicatSet option works.

MONGODB_URI="mongodb://localhost:27017,localhost:27018,localhost:27019/"
        'mongodb' => [
            'driver' => 'mongodb',
            'dsn' => env('MONGODB_URI'),
            'database' => 'laravel',
            'options' => [
                'replicaSet' => 'myRS',
            ]
        ]

You can also pass the list of hosts like this:

        'mongodb' => [
            'driver' => 'mongodb',
            'host' => [
                '127.0.0.1:27017',
                '127.0.0.1:27018',
                '127.0.0.1:27019',
            ],
            'database' => 'laravel',
            'options' => [
                'replicaSet' => 'myRS',
            ]
        ]


When connecting to a replica set, the library that {+odm-short+} 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 :manual:`Replica Set Primary </core/replica-set-primary/>`
in the {+server-docs-name+}.

.. 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
:manual:`Deploy a Replica Set </tutorial/deploy-replica-set/>` in the
{+server-docs-name+}.

Direct Connection
`````````````````

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
:manual:`secondary read preference entry </core/read-preference/#mongodb-readmode-secondary>`
in the {+server-docs-name+}.

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

.. code-block:: bash
:caption: Sample .env environment configuration to enable a direct connection

DB_URI="mongodb://host2:27017/?directConnection=true&readPreference=secondary"


Binary file added docs/includes/figures/connection_uri_parts.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading