(mongodb >=1.0.0)
MongoDB\Driver\Manager::__construct — Create new MongoDB Manager
$uri = null, ?array $uriOptions = null, ?array $driverOptions = null)Constructs a new MongoDB\Driver\Manager object with the specified options.
Note: Per the » Server Discovery and Monitoring Specification, this constructor performs no I/O. Connections will be initialized on demand, when the first operation is executed.
Note: When specifying any SSL or TLS URI options via the connection string or
uriOptionsparameter, the extension will implicitly enable TLS for its connections. To avoid this, either explicitly disable thetlsoption or don't specify any TLS options.
Note: On Unix platforms, the extension is sensitive to scripts that use the fork() system call without also calling exec(). Users are advised not to re-use MongoDB\Driver\Manager instances in a forked child process.
uriA » mongodb:// connection URI:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[defaultAuthDb][?options]]
Defaults to "mongodb://127.0.0.1:27017" if unspecified.
For details on supported URI options, see » Connection String Options in the MongoDB manual. » Connection pool options are not supported, as the extension does not implement connection pools.
The uri is a URL, hence any special characters in its components need to be URL 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.
The defaultAuthDb component may be used to specify the database name associated with the user's credentials; however the authSource URI option will take priority if specified. If neither defaultAuthDb nor authSource are specified, the admin database will be used by default. The defaultAuthDb component has no effect in the absence of user credentials.
uriOptionsAdditional » connection string options, which will overwrite any options with the same name in the uri parameter.
| Option | Type | Description |
|---|---|---|
| appname | string | MongoDB 3.4+ has the ability to annotate connections with metadata provided by the connecting client. This metadata is included in the server's logs upon establishing a connection and also recorded in slow query logs when database profiling is enabled. This option may be used to specify an application name, which will be included in the metadata. The value cannot exceed 128 characters in length. |
| authMechanism | string | The authentication mechanism that MongoDB will use to authenticate the connection. For additional details and a list of supported values, see » Authentication Options in the MongoDB manual. |
| authMechanismProperties | array | Properties for the selected authentication mechanism. For additional details and a list of supported properties, see the » Driver Authentication Specification.
|
| authSource | string | The database name associated with the user's credentials. Defaults to the database component of the connection URI, or the For authentication mechanisms that delegate credential storage to other services (e.g. GSSAPI), this should be |
| compressors | string | A prioritized, comma-delimited list of compressors that the client wants to use. Messages are only compressed if the client and server share any compressors in common, and the compressor used in each direction will depend on the individual configuration of the server or driver. See the » Driver Compression Specification for more information. |
| connectTimeoutMS | int | The time in milliseconds to attempt a connection before timing out. Defaults to 10,000 milliseconds. |
| directConnection | bool | This option can be used to control replica set discovery behavior when only a single host is provided in the connection string. By default, providing a single member in the connection string will establish a direct connection or discover additional members depending on whether the |
| heartbeatFrequencyMS | int | Specifies the interval in milliseconds between the driver's checks of the MongoDB topology, counted from the end of the previous check until the beginning of the next one. Defaults to 60,000 milliseconds. Per the » Server Discovery and Monitoring Specification, this value cannot be less than 500 milliseconds. |
| journal | bool | Corresponds to the default write concern's |
| loadBalanced | bool | Specifies whether the driver is connecting to a MongoDB cluster through a load balancer. If |
| localThresholdMS | int | The size in milliseconds of the latency window for selecting among multiple suitable MongoDB instances while resolving a read preference. Defaults to 15 milliseconds. |
| maxStalenessSeconds | int | Corresponds to the read preference's If specified, the max staleness must be a signed 32-bit integer greater than or equal to |
| password | string | The password for the user being authenticated. This option is useful if the password contains special characters, which would otherwise need to be URL encoded for the connection URI. |
| readConcernLevel | string | Corresponds to the read concern's level parameter. Specifies the level of read isolation. For details, see MongoDB\Driver\ReadConcern. |
| readPreference | string | Corresponds to the read preference's |
| readPreferenceTags | array | Corresponds to the read preference's
|
| replicaSet | string | Specifies the name of the replica set. |
| retryReads | bool | Specifies whether or not the driver should automatically retry certain read operations that fail due to transient network errors or replica set elections. This functionality requires MongoDB 3.6+. Defaults to See the » Retryable Reads Specification for more information. |
| retryWrites | bool | Specifies whether or not the driver should automatically retry certain write operations that fail due to transient network errors or replica set elections. This functionality requires MongoDB 3.6+. Defaults to See » Retryable Writes in the MongoDB manual for more information. |
| serverSelectionTimeoutMS | int | Specifies how long in milliseconds to block for server selection before throwing an exception. Defaults to 30,000 milliseconds. |
| serverSelectionTryOnce | bool | When |
| socketCheckIntervalMS | int | If a socket has not been used recently, the driver must check it via a |
| socketTimeoutMS | int | The time in milliseconds to attempt a send or receive on a socket before timing out. Defaults to 300,000 milliseconds (i.e. five minutes). |
| srvMaxHosts | int | The maximum number of SRV results to randomly select when initially populating the seedlist or, during SRV polling, adding new hosts to the topology. Defaults to |
| srvServiceName | string | The service name to use for SRV lookup in initial DNS seedlist discovery and SRV polling. Defaults to |
| tls | bool | Initiates the connection with TLS/SSL if |
| tlsAllowInvalidCertificates | bool | Specifies whether or not the driver should error when the server's TLS certificate is invalid. Defaults to Warning Disabling certificate validation creates a vulnerability. |
| tlsAllowInvalidHostnames | bool | Specifies whether or not the driver should error when there is a mismatch between the server's hostname and the hostname specified by the TLS certificate. Defaults to Warning Disabling certificate validation creates a vulnerability. Allowing invalid hostnames may expose the driver to a » man-in-the-middle attack. |
| tlsCAFile | string | Path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection. The system certificate store will be used by default. |
| tlsCertificateKeyFile | string | Path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated. |
| tlsCertificateKeyFilePassword | string | Password to decrypt the client private key (i.e. |
| tlsDisableCertificateRevocationCheck | bool | If |
| tlsDisableOCSPEndpointCheck | bool | If |
| tlsInsecure | bool | Relax TLS constraints as much as possible. Specifying Warning Disabling certificate validation creates a vulnerability. Allowing invalid hostnames may expose the driver to a » man-in-the-middle attack. |
| username | string | The username for the user being authenticated. This option is useful if the username contains special characters, which would otherwise need to be URL encoded for the connection URI. |
| w | int|string | Corresponds to the default write concern's |
| wTimeoutMS | int|string | Corresponds to the default write concern's If specified, |
| zlibCompressionLevel | int | Specifies the compression level to use for the zlib compressor. This option has no effect if |
driverOptions| Option | Type | Description |
|---|---|---|
| autoEncryption | array | Provides options to enable automatic client-side field level encryption. The list of options is described in the table below.
|
Path to a correctly hashed certificate directory. The system certificate store will be used by default.
If true, this Manager will use a new libmongoc client, which will not be persisted or shared with other Manager objects. When this Manager object is freed, its client will be destroyed and any connections will be closed. Defaults to false.
Note: Disabling client persistence is not generally recommended.
Allows a higher level library to append its own metadata to the server handshake. By default, the extension submits its own name, version, and platform (i.e. PHP version) in the handshake. Strings can be specified for the "name", "version", and "platform" keys of this array, and will be appended to the respective field(s) in the handshake document.
Note: Handshake information is limited to 512 bytes. The extension will truncate handshake data to fit within this 512-byte string. Higher level libraries are encouraged to keep their own metadata concise.
This option is used to declare a server API version for the manager. If omitted, no API version is declared.
Options supported by automatic encryption through the autoEncryption driver option:
| Option | Type | Description |
|---|---|---|
| keyVaultClient | MongoDB\Driver\Manager | The Manager used to route data key queries to a separate MongoDB cluster. By default, the current Manager and cluster is used. |
| keyVaultNamespace | string | A fully qualified namespace (e.g. "databaseName.collectionName") denoting the collection that contains all data keys used for encryption and decryption. This option is required. |
| kmsProviders | array | A document containing the configuration for one or more KMS providers, which are used to encrypt data keys. Supported providers include If an empty document is specified for The format for aws: {
accessKeyId: <string>,
secretAccessKey: <string>,
sessionToken: <optional string>
}The format for azure: {
tenantId: <string>,
clientId: <string>,
clientSecret: <string>,
identityPlatformEndpoint: <optional string> // Defaults to "login.microsoftonline.com"
}The format for gcp: {
email: <string>,
privateKey: <base64 string>|<MongoDB\BSON\Binary>,
endpoint: <optional string> // Defaults to "oauth2.googleapis.com"
}The format for kmip: {
endpoint: <string>
}The format for local: {
// 96-byte master key used to encrypt/decrypt data keys
key: <base64 string>|<MongoDB\BSON\Binary>
} |
| tlsOptions | array | A document containing the TLS configuration for one or more KMS providers. Supported providers include <provider>: {
tlsCaFile: <optional string>,
tlsCertificateKeyFile: <optional string>,
tlsCertificateKeyFilePassword: <optional string>,
tlsDisableOCSPEndpointCheck: <optional bool>
} |
| schemaMap | array|object | Map of collection namespaces to a local JSON schema. This is used to configure automatic encryption. See » Automatic Encryption Rules in the MongoDB manual for more information. It is an error to specify a collection in both
|
| bypassAutoEncryption | bool | If true, mongocryptd will not be spawned automatically. This is used to disable automatic encryption. Defaults to false. |
| bypassQueryAnalysis | bool | If |
| encryptedFieldsMap | array|object | Map of collection namespaces to an
|
| extraOptions | array | The
See the » Client-Side Encryption Specification for more information. |
Note: Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error. To bypass automatic encryption for all operations, set
bypassAutoEncryption=trueinautoEncryption. For more information on allowed operations, see the » Client-Side Encryption Specification.
uri format is invalid| Version | Description |
|---|---|
| PECL mongodb 2.0.0 | The The The The The The The The The The |
| PECL mongodb 1.16.0 | The AWS KMS provider for client-side encryption now accepts a Added If an empty document is specified for the |
| PECL mongodb 1.15.0 | If an empty document is specified for the |
| PECL mongodb 1.14.0 | Added the |
| PECL mongodb 1.13.0 | Added the |
| PECL mongodb 1.12.0 | KMIP is now supported as a KMS provider for client-side encryption and may be configured in the |
| PECL mongodb 1.11.0 | Added the |
| PECL mongodb 1.10.0 | Added the Azure and GCP are now supported as KMS providers for client-side encryption and may be configured in the |
| PECL mongodb 1.8.0 | Added the Added the |
| PECL mongodb 1.7.0 | Added the Specifying any SSL or TLS option via the |
| PECL mongodb 1.6.0 | Added the The Specifying any SSL or TLS URI option via the connection string or |
| PECL mongodb 1.5.0 |
|
| PECL mongodb 1.4.0 | Added the |
| PECL mongodb 1.3.0 | The |
| PECL mongodb 1.2.0 | The Added the Added the The PHP Streams API is no longer used for socket communication. The |
| PECL mongodb 1.1.0 | The |
Example #1 MongoDB\Driver\Manager::__construct() basic examples
Connecting to standalone MongoDB node:
<?php
$manager = new MongoDB\Driver\Manager("mongodb://example.com:27017");
?>Connecting to standalone MongoDB node via a Unix domain socket. The socket path may include special characters such as slashes and should be encoded with rawurlencode().
<?php
$manager = new MongoDB\Driver\Manager("mongodb://" . rawurlencode("/tmp/mongodb-27017.sock"));
?>Connecting to a replica set:
<?php
$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");
?>Connecting to a sharded cluster (i.e. one or more mongos instances):
<?php
$manager = new MongoDB\Driver\Manager("mongodb://mongos1.example.com,mongos2.example.com/");
?>Connecting to MongoDB with authentication credentials for a particular user and database:
<?php
$manager = new MongoDB\Driver\Manager("mongodb://myusername:[email protected]/?authSource=databaseName");
?>Connecting to MongoDB with authentication credentials for a particular user and database, where the username or password includes special characters (e.g. @, :, %). In the following example, the password string myp@ss:w%rd has been manually escaped; however, rawurlencode() may also be used to escape URI components that may contain special characters.
<?php
$manager = new MongoDB\Driver\Manager("mongodb://myusername:myp%40ss%3Aw%[email protected]/?authSource=databaseName");
?>Connecting to MongoDB with X509 authentication:
<?php
$manager = new MongoDB\Driver\Manager(
"mongodb://example.com/?ssl=true&authMechanism=MONGODB-X509",
[],
[
"pem_file" => "/path/to/client.pem",
]
);
?>