- Tutorials >
- Connecting to MongoDB
Connecting to MongoDB
On this page
Creating a Client instance
Connecting to a Standalone server
If you do not specify a $uri
value, the driver connects to a standalone
mongod on 127.0.0.1
via port 27017
. To connect to a different
server, pass the corresponding connection string as the first parameter when
creating the Client
instance:
Connecting to a Replica Set
The following example demonstrates how to connect to a replica set with a custom read preference:
Connecting with SSL and Authentication
The following example demonstrates how to connect to a MongoDB replica set with SSL and authentication, as is used for MongoDB Atlas:
Alternatively, the authentication credentials and URI parameters may be
specified in the constructor’s $uriOptions
parameter:
The driver supports additional SSL options,
which may be specified in the constructor’s $driverOptions
parameter. Those
options are covered in the MongoDB\Driver\Manager::__construct() documentation.
Specifying connection options
Connection options can be passed via the $uri
parameter, or through the
$options
and $driverOptions
parameters. The available options are
documented in the MongoDB\Client::__construct()
reference.