Navigation
This version of the documentation is archived and no longer supported. To learn how to upgrade your version of PHP Library Manual, refer to the upgrade documentation.

MongoDB\Client::__construct()

Definition

MongoDB\Client::__construct

Constructs a new Client instance.

function __construct($uri = 'mongodb://127.0.0.1/', array $uriOptions = [], array $driverOptions = [])

This constructor has the following parameters:

Parameter Type Description
$uri string

Optional. The URI of the standalone, replica set, or sharded cluster to which to connect. Refer to Connection String URI Format in the MongoDB manual for more information.

Defaults to "mongodb://127.0.0.1:27017" if unspecified.

Any special characters in the URI components need to be encoded according to RFC 3986. This is particularly relevant to the username and password, which can often include special characters such as @, :, or %. When connecting via a Unix domain socket, the socket path may contain special characters such as slashes and must be encoded. The rawurlencode() function may be used to encode constituent parts of the URI.

$uriOptions array

Optional. Specifies additional URI options, such as authentication credentials or query string parameters. The options specified in $uriOptions take precedence over any analogous options present in the $uri string and do not need to be encoded according to RFC 3986.

Refer to the MongoDB\Driver\Manager::__construct() extension reference and MongoDB connection string documentation for accepted options.

$driverOptions array Optional. Specify driver-specific options, such as SSL options. In addition to any options supported by the extension, the MongoDB PHP Library allows you to specify a default type map to apply to the cursors it creates.

The $driverOptions parameter supports the following options:

Option Type Description
typeMap array

Optional. Default type map to apply to cursors, which determines how BSON documents are converted to PHP values. The MongoDB PHP Library uses the following type map by default:

[
    'array' => 'MongoDB\Model\BSONArray',
    'document' => 'MongoDB\Model\BSONDocument',
    'root' => 'MongoDB\Model\BSONDocument',
]
allow_invalid_hostname boolean

Optional. Disables hostname validation if true. Defaults to false.

Allowing invalid hostnames may expose the driver to a man-in-the-middle attack.

ca_dir string

Optional. Path to a correctly hashed certificate directory. The system certificate store will be used by default.

Falls back to the deprecated capath SSL context option if not specified.

ca_file string

Optional. Path to a certificate authority file. The system certificate store will be used by default.

Falls back to the deprecated cafile SSL context option if not specified.

crl_file string Optional. Path to a certificate revocation list file.
pem_file string

Optional. Path to a PEM encoded certificate to use for client authentication.

Falls back to the deprecated local_cert SSL context option if not specified.

pem_pwd string

Optional. Passphrase for the PEM encoded certificate (if applicable).

Falls back to the deprecated passphrase SSL context option if not specified.

weak_cert_validation boolean

Optional. Disables certificate validation true. Defaults to false.

Falls back to the deprecated allow_self_signed SSL context option if not specified.

context resource

Optional. SSL context options to be used as fallbacks for other driver options (as specified). Note that the driver does not consult the default stream context.

This option is supported for backwards compatibility, but should be considered deprecated.

Errors/Exceptions

MongoDB\Exception\InvalidArgumentException for errors related to the parsing of parameters or options.

MongoDB\Driver\Exception\InvalidArgumentException for errors related to the parsing of parameters or options at the driver level.

MongoDB\Driver\Exception\RuntimeException for other errors at the driver level (e.g. connection errors).

Behavior

A MongoDB\Driver\Manager is constructed internally. Per the Server Discovery and Monitoring specification, MongoDB\Driver\Manager::__construct() performs no I/O. Connections will be initialized on demand, when the first operation is executed.

Examples

Connecting to a Replica Set

If you do not specify a $uri value, the driver connects to a standalone mongod on 127.0.0.1 via port 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',
    ]
);

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:

<?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.

Specifying a Custom Type Map

By default, the MongoDB PHP Library deserializes BSON documents and arrays as MongoDB\Model\BSONDocument and MongoDB\Model\BSONArray objects, respectively. The following example demonstrates how to have the library unserialize everything as a PHP array, as was done in the legacy mongo extension.

<?php

$client = new MongoDB\Client(
    null,
    [],
    [
        'typeMap' => [
            'root' => 'array',
            'document' => 'array',
            'array' => 'array',
        ],
    ]
);