class MongoClient (View source)

A connection between PHP and MongoDB. This class is used to create and manage connections See MongoClient::__construct() and the section on connecting for more information about creating connections.

Constants

VERSION

DEFAULT_HOST

DEFAULT_PORT

RP_PRIMARY

RP_PRIMARY_PREFERRED

RP_SECONDARY

RP_SECONDARY_PREFERRED

RP_NEAREST

Properties

$connected
$status
protected $server
protected $persistent

Methods

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

Creates a new database connection object

bool
close(bool|string $connection)

(PECL mongo >= 1.3.0)
Closes this database connection This method does not need to be called, except in unusual circumstances.

bool
connect()

Connects to a database server

array
dropDB(mixed $db)

Drops a database

__get(string $dbname)

(PECL mongo >= 1.3.0)
Gets a database

static array
getConnections()

Get connections Returns an array of all open connections, and information about each of the servers

array
getHosts()

Get hosts This method is only useful with a connection to a replica set. It returns the status of all of the hosts in the set. Without a replica set, it will just return an array with one element containing the host that you are connected to.

array
getReadPreference()

Get read preference Get the read preference for this connection

array
getWriteConcern()

(PECL mongo >= 1.5.0)
Get the write concern for this connection

killCursor(string $server_hash, int|MongoInt64 $id)

Kills a specific cursor on the server

array
listDBs()

(PECL mongo >= 1.3.0)
Lists all of the databases available

selectCollection(string $db, string $collection)

(PECL mongo >= 1.3.0)
Gets a database collection

selectDB(string $name)

(PECL mongo >= 1.3.0)
Gets a database

bool
setReadPreference(string $readPreference, array $tags = null)

(PECL mongo >= 1.3.0)
Set read preference

string
switchSlave()

(PECL mongo >= 1.1.0)
Choose a new secondary for slaveOkay reads

string
__toString()

String representation of this connection

Details

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

Creates a new database connection object

Parameters

string $server

[optional] The server name.

array $options

[optional] An array of options for the connection. Currently available options include: "connect" If the constructor should connect before returning. Default is true. "timeout" For how long the driver should try to connect to the database (in milliseconds). "replicaSet" The name of the replica set to connect to. If this is given, the master will be determined by using the ismaster database command on the seeds, so the driver may end up connecting to a server that was not even listed. See the replica set example below for details. "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. "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. "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. "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).

array $driver_options

[optional]

An array of options for the MongoDB driver. Options include setting connection https://php.net/manual/en/mongo.connecting.ssl.php#mongo.connecting.context.ssl context options for SSL or https://php.net/manual/en/context.mongodb.php 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 https://php.net/manual/en/context.ssl.php SSL context options. See the https://php.net/manual/en/mongo.connecting.ssl.php#mongo.connecting.context.ssl Connecting over SSL tutorial.

Exceptions

MongoConnectionException

bool close(bool|string $connection)

(PECL mongo >= 1.3.0)
Closes this database connection This method does not need to be called, except in unusual circumstances.

The driver will cleanly close the database connection when the Mongo object goes out of scope.

Parameters

bool|string $connection

[optional]

If connection is not given, or FALSE then connection that would be selected for writes would be closed. In a single-node configuration, that is then the whole connection, but if you are connected to a replica set, close() will only close the connection to the primary server. If connection is TRUE then all connections as known by the connection manager will be closed. This can include connections that are not referenced in the connection string used to create the object that you are calling close on. If connection is a string argument, then it will only close the connection identified by this hash. Hashes are identifiers for a connection and can be obtained by calling {\MongoClient::getConnections()}.

Return Value

bool

If the connection was successfully closed.

bool connect()

Connects to a database server

Return Value

bool

If the connection was successful.

Exceptions

MongoConnectionException

array dropDB(mixed $db)

Drops a database

Parameters

mixed $db

The database to drop. Can be a MongoDB object or the name of the database.

Return Value

array

The database response.

MongoDB __get(string $dbname)

(PECL mongo >= 1.3.0)
Gets a database

Parameters

string $dbname

The database name.

Return Value

MongoDB

The database name.

static array getConnections()

Get connections Returns an array of all open connections, and information about each of the servers

Return Value

array

array getHosts()

Get hosts This method is only useful with a connection to a replica set. It returns the status of all of the hosts in the set. Without a replica set, it will just return an array with one element containing the host that you are connected to.

Return Value

array

array getReadPreference()

Get read preference Get the read preference for this connection

Return Value

array

array getWriteConcern()

(PECL mongo >= 1.5.0)
Get the write concern for this connection

Return Value

array

This function returns an array describing the write concern. The array contains the values w for an integer acknowledgement level or string mode, and wtimeout denoting the maximum number of milliseconds to wait for the server to satisfy the write concern.

killCursor(string $server_hash, int|MongoInt64 $id)

Kills a specific cursor on the server

Parameters

string $server_hash

The server hash that has the cursor. This can be obtained through https://secure.php.net/manual/en/mongocursor.info.php MongoCursor::info().

int|MongoInt64 $id

The ID of the cursor to kill. You can either supply an https://secure.php.net/manual/en/language.types.integer.php int containing the 64 bit cursor ID, or an object of the https://secure.php.net/manual/en/class.mongoint64.php MongoInt64 class. The latter is necessary on 32 bit platforms (and Windows).

array listDBs()

(PECL mongo >= 1.3.0)
Lists all of the databases available

Return Value

array

Returns an associative array containing three fields. The first field is databases, which in turn contains an array. Each element of the array is an associative array corresponding to a database, giving the database's name, size, and if it's empty. The other two fields are totalSize (in bytes) and ok, which is 1 if this method ran successfully.

MongoCollection selectCollection(string $db, string $collection)

(PECL mongo >= 1.3.0)
Gets a database collection

Parameters

string $db

The database name.

string $collection

The collection name.

Return Value

MongoCollection

Returns a new collection object.

Exceptions

Exception

MongoDB selectDB(string $name)

(PECL mongo >= 1.3.0)
Gets a database

Parameters

string $name

The database name.

Return Value

MongoDB

Returns a new db object.

Exceptions

InvalidArgumentException

bool setReadPreference(string $readPreference, array $tags = null)

(PECL mongo >= 1.3.0)
Set read preference

Parameters

string $readPreference
array $tags

Return Value

bool

string switchSlave()

(PECL mongo >= 1.1.0)
Choose a new secondary for slaveOkay reads

Return Value

string

The address of the secondary this connection is using for reads. This may be the same as the previous address as addresses are randomly chosen. It may return only one address if only one secondary (or only the primary) is available. For example, if we had a three member replica set with a primary, secondary, and arbiter this method would always return the address of the secondary. If the secondary became unavailable, this method would always return the address of the primary. If the primary also became unavailable, this method would throw an exception, as an arbiter cannot handle reads.

Exceptions

MongoException

string __toString()

String representation of this connection

Return Value

string

Returns hostname and port for this connection.