Create a MongoDB Client
Overview
To connect to a MongoDB deployment, you must create the following items:
Connection URI, also known as a connection string, which tells the PHP library which MongoDB deployment to connect to.
MongoDB\Client object, which creates the connection to the MongoDB deployment and lets you perform operations on it.
You can also set options within either or both of these components to customize the way that the PHP library behaves while connected to MongoDB.
This guide describes the components of a connection string and shows how to
use a MongoDB\Client
object to connect to a MongoDB deployment.
Connection URI
A standard connection string includes the following components:
Component | Description |
---|---|
| Required. A prefix that identifies this as a string in the standard connection format. |
| Optional. Authentication credentials. If you include these, the client
authenticates the user against the database specified in |
| Required. The host and optional port number where MongoDB is running. If you don't
include the port number, the driver uses the default port, |
| Optional. The authentication database to use if the
connection string includes |
| Optional. A query string that specifies connection-specific
options as |
To learn more about connection strings, see Connection Strings in the Server manual.
Create a MongoDB\Client
To create a connection to MongoDB, construct a MongoDB\Client
object.
Pass the following parameters to the MongoDB\Client
constructor:
$uri
: Sets the connection URI.$uriOptions
: (Optional) Sets URI options to configure how the client connects to MongoDB, including authentication credentials and server selection settings. If you set the same options in this parameter and in your connection string, the$uriOptions
values take precedence. To view a full list of supported options, see the Specify Connection Options guide.$driverOptions
: (Optional) Sets options to configure the behavior of the underlying PHP extension, including data encryption settings and certificate validation options for TLS connections. To view a full list of supported options, seeMongoDB\Client::__construct()
in the API documentation.
Example
This example constructs a client and passes the following parameters:
Connection URI, which connects to a MongoDB deployment on port
27017
oflocalhost
URI options parameter, which instructs the PHP library to wait
10000
milliseconds for server selection before generating an error
$uri = 'mongodb://localhost:27017'; $uriOptions = ['serverSelectionTimeoutMS' => 10000]; $client = new MongoDB\Client($uri, $uriOptions);
API Documentation
To learn more about creating a MongoDB\Client
object in the PHP library,
see the following API documentation: