Navigation

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
autoEncryption array Optional. Options to configure client-side field-level encryption in the driver. The encryption options are documented in the extension documentation. For the keyVaultClient option, you may pass a MongoDB\Client instance, which will be unwrapped to provide a MongoDB\Driver\Manager to the extension. .. versionadded:: 1.6
driver array

Optional. Additional driver metadata to be passed on to the server handshake. This is an array containing name, version, and platform fields:

[
    'name' => 'my-driver',
    'version' => '1.2.3-dev',
    'platform' => 'some-platform',
]

Note

This feature is primarily designed for custom drivers and ODMs, which may want to identify themselves to the server for diagnostic purposes. Applications should use the appName URI option instead of driver metadata.

New in version 1.7.

serverApi MongoDB\Driver\ServerApi

Optional. Used to declare an API version on the client. See the Versioned API tutorial for usage.

New in version 1.9.

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.

Deprecated since version 1.6: This option has been deprecated. Use the tlsAllowInvalidHostnames URI option instead.

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.

Deprecated since version 1.6: This option has been deprecated. Use the tlsCAFile URI option instead.

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.

Deprecated since version 1.6: This option has been deprecated. Use the tlsCertificateKeyFile URI option instead.

pem_pwd string

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

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

Deprecated since version 1.6: This option has been deprecated. Use the tlsCertificateKeyFilePassword URI option instead.

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.

Deprecated since version 1.6: This option has been deprecated. Use the tlsAllowInvalidCertificates URI option instead.

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',
        ],
    ]
);