PHP 7.0.6 Released

MongoClient::__construct

(PECL mongo >=1.3.0)

MongoClient::__constructCreates a new database connection object

Description

public MongoClient::__construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) [, array $driver_options ]]] )

If no parameters are passed, this connects to "localhost:27017" (or whatever was specified in php.ini for mongo.default_host and mongo.default_port).

server should have the form:

mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db

The connection string always starts with mongodb://, to indicate it is a connection string in this form.

If username and password are specified, the constructor will attempt to authenticate the connection with the database before returning. Username and password are optional and must be followed by an @, if specified.

At least one host must be given (port optional, always defaulting to 27017) and as many hosts as desired may be connected to. Host names are comma-separated and the constructor will return successfully if it connected to at least one host. If it could not connect to any of the hosts, it will throw a MongoConnectionException. Please see the Replica Sets section for information on how to connect to Replica Sets.

If you specified a username and password, you may specify a database to authenticate with. If db is not specified, "admin" will be used.

An optional query string may be used to specify extra options. The same options are supported through the options array as well, and are therefore redescribed there. See the examples below on how to set those options.

One part of the options governs how the driver reads from secondary nodes in a replica set environment. Extra information on how these read preferences work is available as well through the read preferences documentation page.

Parameters

server

The server name.

options

An array of options for the connection. Currently available options include:

  • "authMechanism"

    Available mechanisms are:

    authMechanism Description Availability
    MONGODB-CR Authenticate using Challenge Response mechanism. This is the default value. All MongoDB versions
    X509 Authenticates using X509 certificates MongoDB 2.6. Only available when OpenSSL is enabled
    PLAIN Authenticates using unencrypted plain username+password. Must be used over SSL connections. Generally used by MongoDB to login via 3rd party LDAP server MongoDB Enterprise 2.4. The Driver must be compiled against CyrusSASL2
    GSSAPI Authenticates via kerberos systems MongoDB Enterprise 2.4. The Driver must be compiled against CyrusSASL2

  • "authSource"

    Should be set to the database name where the user is defined it.

  • "connect"

    If the constructor should connect before returning. Default is TRUE. When set to FALSE the driver will automatically connect to the server whenever it is necessary to do a query. Alternatively, you can run MongoClient::connect() manually.

    Warning

    This option is not supported through the connection string.

  • "connectTimeoutMS"

    How long a connection can take to be opened before timing out in milliseconds. Defaults to 60000 (60 seconds).

    If -1 is specified, no connection timeout will be applied and PHP will use default_socket_timeout.

  • "db"

    The database to authenticate against can be specified here, instead of including it in the host list. This overrides a database given in the host list.

  • "fsync"

    When "fsync" is set, all write operations will block until the database has flushed the changes to disk. This makes the write operations slower, but it guarantees that writes have succeeded and that the operations can be recovered in case of total system failure.

    If the MongoDB server has journaling enabled, this option is identical to "journal". If journaling is not enabled, this option ensures that write operations will be synced to database files on disk.

    Note: If journaling is enabled, users are strongly encouraged to use the "journal" option instead of "fsync". Do not use "fsync" and "journal" simultaneously, as that will result in an error.

  • "journal"

    When "journal" is set, all write operations will block until the database has flushed the changes to the journal on disk. This makes the write operations slower, but it guarantees that writes have succeeded and that the operations can be recovered in case of total system failure.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "gssapiServiceName"

    Sets the » Kerberos service principal. Only applicable when authMechanism=GSSAPI. Defaults to "mongodb".

  • "password"

    The password can be specified here, instead of including it in the host list. This is especially useful if a password has a "@" in it. This overrides a password set in the host list.

  • "readPreference"

    Specifies the read preference type. Read preferences provide you with control from which secondaries data can be read from.

    Allowed values are: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED and MongoClient::RP_NEAREST.

    See the documentation on read preferences for more information.

  • "readPreferenceTags"

    Specifies the read preference tags as an array of strings. Tags can be used in combination with the readPreference option to further control which secondaries data might be read from.

    See the documentation on read preferences for more information.

  • "replicaSet"

    The name of the replica set to connect to. If this is given, the primary will be automatically be determined. This means that the driver may end up connecting to a server that was not even listed. See the replica set example below for details.

  • "secondaryAcceptableLatencyMS"

    When reading from a secondary (using ReadPreferences), do not read from secondaries known to be more then secondaryAcceptableLatencyMS away from us. Defaults to 15

  • "socketTimeoutMS"

    How long a socket operation (read or write) can take before timing out in milliseconds. Defaults to 30000 (30 seconds).

    If -1 is specified, socket operations may block indefinitely. This option may also be set on a per-operation basis using MongoCursor::timeout() for queries or the "socketTimeoutMS" option for write methods.

    Note: This is a client-side timeout. If a write operation times out, there is no way to know if the server actually handled the write or not, as a MongoCursorTimeoutException will be thrown in lieu of returning a write result.

  • "ssl"

    A boolean to specify whether you want to enable SSL for the connections to MongoDB. Extra options such as certificates can be set with SSL context options.

  • "username"

    The username can be specified here, instead of including it in the host list. This is especially useful if a username has a ":" in it. This overrides a username set in the host list.

  • "w"

    The w option specifies the Write Concern for the driver, which determines how long the driver blocks when writing. The default value is 1.

    This option is applicable when connecting to both single servers and replica sets. A positive value controls how many nodes must acknowledge the write instruction before the driver continues. A value of 1 would require the single server or primary (in a replica set) to acknowledge the write operation. A value of 3 would cause the driver to block until the write has been applied to the primary as well as two secondary servers (in a replica set).

    A string value is used to control which tag sets are taken into account for write concerns. "majority" is special and ensures that the write operation has been applied to the majority (more than 50%) of the participating nodes.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable for write operations where "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "slaveOkay"

    Deprecated. Please use the read preference options.

  • "timeout"

    Deprecated alias for "connectTimeoutMS".

  • "wTimeout"

    Deprecated alias for "wTimeoutMS".

driver_options

An array of options for the MongoDB driver. Options include setting connection context options for SSL or logging callbacks.

  • "context"

    The Stream Context to attach to all new connections. This allows you for example to configure SSL certificates and are described at SSL context options. See the Connecting over SSL tutorial.

Return Values

Returns a new database connection object.

Errors/Exceptions

Throws MongoConnectionException if it tries and fails to connect to the database for all hostnames given. It will also throw a MongoConnnectionException if an invalid username or password is given. See MongoConnectionException documentation for common exceptions and their causes.

Examples

Example #1 MongoClient::__construct() replica set example

This example shows how to connect the driver to a replica set. It assumes that there is a set of three servers: sf1.example.com, sf2.example.com, and ny1.example.com. The primary could be any one of these servers.

<?php

// pass a comma-separated list of server names to the constructor
// Note that we don't need to pass in all the members of the replicaset, the driver 
// will derive the full list.
$m1 = new MongoClient("mongodb://sf2.example.com,ny1.example.com", array("replicaSet" => "myReplSet"));

?>

If the current primary fails, the driver will figure out which secondary server became the new primary and automatically start using that connection. Automatic failover will not work correctly if replicaSet is not specified.

At least one seed in the seed list must be up for the driver to connect to the replica set.

If you include seeds from two separate replica sets, behavior is undefined.

See the » core documentation on replica sets for more information.

Example #2 Connecting to a domain socket

In version 1.0.9+, you can use a UNIX domain socket to connect to an instance of MongoDB running locally. This should be slightly faster than using a network connection.

In version 1.5.0, the MongoDB server automatically opens a socket at /tmp/mongodb-<port>.sock. You can connect to this by specifying the path in your connection string:

<?php

// MongoDB server running locally on port 20000
$m = new MongoClient("mongodb:///tmp/mongodb-20000.sock");

?>

You can combine this with any other connections you'd like:

<?php

// try to connect to the domain socket, fall back to localhost connection
$m = new MongoClient("mongodb:///tmp/mongodb-27017.sock,localhost:27017");

?>

Example #3 MongoClient::__construct() authentication example

A user must exist in the admin database before attempting to use authentication. You can create one with the Mongo shell by running:

> use admin
switched to db admin
> db.addUser("testUser", "testPass");
{
        "_id" : ObjectId("4b21272fd9ab21611d19095c"),
        "user" : "testUser",
        "pwd" : "03b9b27e0abf1865e2f6fcbd9845dd59"
}
>

After creating a user with, in this case, username "testUser" and password "testPass", you can create an authenticated connection:

<?php

$m 
= new MongoClient("mongodb://testUser:testPass@localhost");

?>

Example #4 MongoClient::__construct() read preference example

<?php

// Prefer the nearest server in the "east" data center
$uri  'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>

See the read preferences section of this manual for further information.

Example #5 MongoClient::__construct() options example

Options can be passed both through the query string in the connection string, or as an array passed as second argument to the constructor.

Here we set the journal option to true and readPreference to secondary preferred as default for all write operations:

<?php
$m 
= new MongoClient("mongodb://localhost/?journal=true&readPreference=secondary");
?>

And now we do the same, but as an options array:

<?php
$options 
= array(
    
'journal' => true,
    
'readPreference' => 'secondary',
);
$m = new MongoClient("mongodb://localhost/"$options);
?>

Example #6 MongoClient::__construct() read preference example

<?php

// Prefer the nearest server in the "east" data center
$uri  'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>

See the read preferences section of this manual for further information.

Changelog

Version Description
1.5.0

Added "authMechanism", "gssapiServiceName", and "secondaryAcceptableLatencyMS".

1.4.0

Added "ssl" option and support for connecting over SSL.

Added "wTimeoutMS" option, which replaces "wTimeout".

Emits E_DEPRECATED when "slaveOkay" or "timeout" is used.

1.5.0

Added "authSource".

1.3.4

Added "connectTimeoutMS" and "socketTimeoutMS" options.

1.3.0

Added "readPreference", "readPreferenceTags", "w", and "wTimeout" options.

1.2.0

Added "username" and "password" options.

Removed "persist" option, as all connections are now persistent. It can still be used, but it doesn't affect anything.

"persist"

If the connection should be persistent. If set, the connection will be persistent. The string representation of the value is used as an ID for the connection, so two instances of MongoClient that are initialized with array("persist" => "foobar") will share the same database connection, whereas an instance initialized with array("persist" => "barbaz") will use a different database connection.

The "replicaSet" option now takes a string, not a boolean.

1.0.9 Added "replicaSet" option.
1.0.2

Changed constructor to take an array of options. Pre-1.0.2, the constructor took the following parameters:

server

The server name.

connect

Optional boolean parameter specifying if the constructor should connect to the database before returning. Defaults to TRUE.

persistent

If the connection should be persistent.

paired

If the connection should be paired.

User Contributed Notes

mike at eastghost dot com
2 years ago
HOLY MOLY, 100 to 200 times instant speed boost in one small change.

"In version 1.0.9+, you can use a UNIX domain socket to connect to an instance of MongoDB running locally. This should be slightly faster than using a network connection."

is an EXTREME understatement.  Just trying out stuff, playing around, etc., we changed from

MongoClient( 'mongodb://pri.eastghost.com:27017' etc)

to

MongoClient ( 'mongodb:///tmp/mongodb-27017.sock' etc)

and saw instant 100x-200x speed boost, all else untouched.
page times went from 700 - 1400 (as in 1.4 seconds)
to 7 as in milliseconds.

mongo driver 1.4.1
(for apache 2.6)
mike at eastghost dot com
1 year ago
FOLLOW UP to comment on speed

Now using --
mongo 3.0.1 pre-compiled binaries
using mongo/php-1.6.6. driver from PECL
on php 5.6.0
on apache 2.4
on debian wheezy 7.8

Dropped in mongo 301 binaries
everything else unchanged
restarted apache

instantly started getting "No candidate servers found"
upgraded to mongo/php-1.6.6 driver on pecl
same result

of these four parms to \MongoClient()

A) 'mongodb:///tmp/mongodb-27017.sock'
B) #'mongodb://127.0.0.1:27017'
C) #'mongodb://localhost:27017'
D) #'mongodb://pri.eastghost.com:27017'

A) used to be 100x to 200x faster than B), C) and maybe 400x faster than D), as explained in comment below, but initially (after mongo 3.0.1 drop-in) A) stopped dead.  Tried B, instantly began working.  Went back to A), kept working.  Almost seems as if driver 1.6.6 can not populate candidate servers list when called via unix socket (/tmp/mongodb-27017.sock), but once the list is populated, calling via unix socket magically works fine.

While screwing around with this, all else unchanged, we're now noticing B) and C) seem to be as fast as A), and D) is only slightly slower (due to connect over WAN, instead of local LAN).  This behavior is as it theoretically should be: Maybe the once huge difference in the mongo php driver between unix sockets and localhost has been fixed?  Still testing -- will report back if any slowdown noticed.

see https://groups.google.com/forum/#!topic/mongodb-user/RTBDDMwywzA
mike at eastghost dot com
3 years ago
read somewhere that

$uri  = 'mongodb://rs1.example.com/?w=0';

(the w=0 parm) makes the MongoDB driver accept 'blind writes' without waiting for any confirmation of write success from server.
To Top