(mongodb >=1.0.0)
MongoDB\Driver\Manager::__construct — Create new MongoDB Manager
$uri
= "mongodb://127.0.0.1/"
[, array $uriOptions
= array()
[, array $driverOptions
= array()
]]] )Constructs a new MongoDB\Driver\Manager object with the specified options.
Nota: 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.
Nota: En plataformas Unix, el controlador de MongoDB es susceptible a scripts que utilizan la llamada al sistema fork() sin llamar también a exec(). Los usuarios están advertidos de no reusar instancias de MongoDB\Driver\Manager en un proceso hijo bifurcado («forked»).
uri
A » mongodb:// connection URI:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
For details on supported options, see » Connection String Options in the MongoDB manual. » Connection pool options are not supported, as the PHP driver 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.
uriOptions
Additional
» 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. For authentication mechanisms that delegate credential storage to other services (e.g. GSSAPI), this should be "$external". |
canonicalizeHostname | boolean |
If This option is a deprecated alias for the "CANONICALIZE_HOST_NAME" property of the "authMechanismProperties" URI option. |
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 | integer |
The time in milliseconds to attempt a connection before timing out. Defaults to 10,000 milliseconds. |
gssapiServiceName | string |
Set the Kerberos service name when connecting to Kerberized MongoDB instances. This value must match the service name set on MongoDB instances (i.e. » saslServiceName server parameter). Defaults to "mongodb". This option is a deprecated alias for the "SERVICE_NAME" property of the "authMechanismProperties" URI option. |
heartbeatFrequencyMS | integer |
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 | boolean |
Corresponds to the default write concern's
|
localThresholdMS | integer |
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 | integer |
Corresponds to the read preference's "maxStalenessSeconds". Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. By default, there is no maximum staleness and clients will not consider a secondary’s lag when choosing where to direct a read operation. For details, see MongoDB\Driver\ReadPreference.
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 | boolean |
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 | boolean |
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. |
safe | boolean |
If This option is deprecated and should not be used. |
serverSelectionTimeoutMS | integer |
Specifies how long in milliseconds to block for server selection before throwing an exception. Defaults to 30,000 milliseconds. |
serverSelectionTryOnce | boolean |
When |
slaveOk | boolean |
Specifies "secondaryPreferred" for the read
preference mode if This option is deprecated and should not be used. |
socketCheckIntervalMS | integer |
If a socket has not been used recently, the driver must check it via an isMaster command before using it for any operation. Defaults to 5,000 milliseconds. |
socketTimeoutMS | integer |
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). |
ssl | boolean |
Initiates the connection with TLS/SSL if This option is a deprecated alias for the "tls" URI option. |
tls | boolean |
Initiates the connection with TLS/SSL if |
tlsAllowInvalidCertificates | boolean |
Specifies whether or not the driver should error when the server's
TLS certificate is invalid. Defaults to Advertencia
Disabling certificate validation creates a vulnerability. |
tlsAllowInvalidHostnames | boolean |
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 Advertencia
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. "tlsCertificateKeyFile" URI option) to be used for TLS connections. |
tlsInsecure | boolean |
Relax TLS constraints as much as possible. Specifying Advertencia
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 | integer|string |
Corresponds to the default write concern's |
wTimeoutMS | integer|string |
Corresponds to the default write concern's
If specified, wTimeoutMS must be a signed 32-bit integer greater than or equal to zero. |
zlibCompressionLevel | integer |
Specifies the compression level to use for the zlib compressor. This option has no effect if zlib is not included in the "compressors" URI option. See the » Driver Compression Specification for more information. |
driverOptions
Option | Type | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
allow_invalid_hostname | boolean |
Disables hostname validation if Allowing invalid hostnames may expose the driver to a » man-in-the-middle attack. This option is a deprecated alias for the "tlsAllowInvalidHostnames" URI option. |
||||||||||||
ca_dir | string |
Path to a correctly hashed certificate directory. The system certificate store will be used by default. |
||||||||||||
ca_file | 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. This option is a deprecated alias for the "tlsCAFile" URI option. |
||||||||||||
context | resource |
SSL context options to be used as fallbacks if a driver option or its equivalent URI option, if any, is not specified. Note that the driver does not consult the default stream context (i.e. stream_context_get_default()). The following context options are supported:
This option is supported for backwards compatibility, but should be considered deprecated. |
||||||||||||
crl_file | string | Path to a certificate revocation list file. | ||||||||||||
pem_file | string |
Path to a PEM encoded certificate to use for client authentication. This option is a deprecated alias for the "tlsCertificateKeyFile" URI option. |
||||||||||||
pem_pwd | string |
Passphrase for the PEM encoded certificate (if applicable). This option is a deprecated alias for the "tlsCertificateKeyFilePassword" URI option. |
||||||||||||
weak_cert_validation | boolean |
Disables certificate validation if This option is a deprecated alias for the "tlsAllowInvalidHostnames" URI option. |
uri
format is invalid
Versión | Descripción |
---|---|
1.6.0 |
Added the "retryReads", "tls", "tlsAllowInvalidCertificates", "tlsAllowInvalidHostnames", "tlsCAFile", "tlsCertificateKeyFile", "tlsCertificateKeyFilePassword", and "tlsInsecure" URI options.
The "retryWrites" URI option defaults to |
1.5.0 |
"wtimeoutMS" is now always validated and applied to the write concern. Previously, the option was ignored if "w" was <= 1, since the timeout only applies to replication. |
1.4.0 |
Added the "compressors", "retryWrites", and "zlibCompressionLevel" URI options. |
1.3.0 |
The |
1.2.0 |
The Added the "appname" URI option. Added the "allow_invalid_hostname", "ca_file", "ca_dir", "clr_file", "pem_file", "pem_pwd", and "weak_cert_validation" driver options. The PHP Streams API is no longer used for socket communication. The "connectTimeoutMS" URI option now defaults to 10 seconds instead of default_socket_timeout in previous versions. Additionally, the driver no longer supports all SSL context options via the "context" driver option. |
1.1.0 |
The |
Ejemplo #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]/mydatabase");
?>
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]/mydatabase");
?>
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",
]
);
?>