Docs Menu

Docs HomePHP Library Manual

Connecting to MongoDB

On this page

  • Creating a Client instance
  • Specifying connection options

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:

<?php
$client = new MongoDB\Client('mongodb://mongodb-deployment:27017');

The following example demonstrates how to connect to a replica set with a custom read preference:

<?php
$client = new MongoDB\Client(
'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet',
[
'readPreference' => 'secondaryPreferred',
]
);

The following example demonstrates how to connect to a MongoDB replica set with SSL and authentication, as is used for MongoDB Atlas:

<?php
$client = new MongoDB\Client(
'mongodb://myUsername:myPassword@rs1.example.com,rs2.example.com/?ssl=true&replicaSet=myReplicaSet&authSource=admin'
);

Alternatively, the authentication credentials and URI parameters may be specified in the constructor's $uriOptions parameter:

<?php
$client = new MongoDB\Client(
'mongodb://rs1.example.com,rs2.example.com/'
[
'username' => 'myUsername',
'password' => 'myPassword',
'ssl' => true,
'replicaSet' => 'myReplicaSet',
'authSource' => 'admin',
],
);

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.

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.

←  TutorialsServer Selection and Monitoring →