class Mongo extends MongoClient (View source)

The connection point between MongoDB and PHP.

This class is used to initiate a connection and for database server commands.

Constants

VERSION

DEFAULT_HOST

DEFAULT_PORT

RP_PRIMARY

RP_PRIMARY_PREFERRED

RP_SECONDARY

RP_SECONDARY_PREFERRED

RP_NEAREST

Properties

$connected from  MongoClient
$status from  MongoClient
protected $server from  MongoClient
protected $persistent from  MongoClient

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

int
getPoolSize()

(PECL mongo >= 1.2.0)
Get pool size for connection pools

bool
getSlave()

(PECL mongo >= 1.1.0)
Returns the address being used by this for slaveOkay reads

bool
getSlaveOkay()

(PECL mongo >= 1.1.0)
Get slaveOkay setting for this connection

bool
pairConnect()

Connects to paired database server

array
poolDebug()

(PECL mongo >= 1.2.0)
Returns information about all connection pools.

bool
setSlaveOkay(bool $ok)

(PECL mongo >= 1.1.0)
Change slaveOkay setting for this connection

bool
setPoolSize(int $size)

(PECL mongo >= 1.2.0)
Set the size for future connection pools.

bool
persistConnect(string $username = "", string $password = "")

Creates a persistent connection with a database server

bool
pairPersistConnect(string $username = "", string $password = "")

Creates a persistent connection with paired database servers

bool
connectUtil()

Connects with a database server

array|null
lastError()

Check if there was an error on the most recent db operation performed

array
prevError()

Checks for the last error thrown during a database operation

array
resetError()

Clears any flagged errors on the connection

bool
forceError()

Creates a database error on the database.

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.

int getPoolSize()

(PECL mongo >= 1.2.0)
Get pool size for connection pools

Return Value

int

Returns the current pool size.

See also

MongoPool::getSize

bool getSlave()

(PECL mongo >= 1.1.0)
Returns the address being used by this for slaveOkay reads

Return Value

bool

The address of the secondary this connection is using for reads.

This returns NULL if this is not connected to a replica set or not yet initialized.

bool getSlaveOkay()

(PECL mongo >= 1.1.0)
Get slaveOkay setting for this connection

Return Value

bool

Returns the value of slaveOkay for this instance.

bool pairConnect()

Connects to paired database server

Return Value

bool

Exceptions

MongoConnectionException

array poolDebug()

(PECL mongo >= 1.2.0)
Returns information about all connection pools.

Return Value

array

Each connection pool has an identifier, which starts with the host. For each pool, this function shows the following fields:

in use

The number of connections currently being used by MongoClient instances. in pool The number of connections currently in the pool (not being used).

remaining

The number of connections that could be created by this pool. For example, suppose a pool had 5 connections remaining and 3 connections in the pool. We could create 8 new instances of MongoClient before we exhausted this pool (assuming no instances of MongoClient went out of scope, returning their connections to the pool). A negative number means that this pool will spawn unlimited connections. Before a pool is created, you can change the max number of connections by calling Mongo::setPoolSize(). Once a pool is showing up in the output of this function, its size cannot be changed.

timeout

The socket timeout for connections in this pool. This is how long connections in this pool will attempt to connect to a server before giving up.

See also

MongoPool::info

bool setSlaveOkay(bool $ok)

(PECL mongo >= 1.1.0)
Change slaveOkay setting for this connection

Parameters

bool $ok

[optional]

If reads should be sent to secondary members of a replica set for all possible queries using this {\MongoClient} instance.

Return Value

bool

returns the former value of slaveOkay for this instance.

bool setPoolSize(int $size)

(PECL mongo >= 1.2.0)
Set the size for future connection pools.

Parameters

int $size

The max number of connections future pools will be able to create. Negative numbers mean that the pool will spawn an infinite number of connections.

Return Value

bool

Returns the former value of pool size.

See also

MongoPool::setSize

bool persistConnect(string $username = "", string $password = "")

Creates a persistent connection with a database server

Parameters

string $username

A username used to identify the connection.

string $password

A password used to identify the connection.

Return Value

bool

If the connection was successful.

Exceptions

MongoConnectionException

bool pairPersistConnect(string $username = "", string $password = "")

Creates a persistent connection with paired database servers

Parameters

string $username

A username used to identify the connection.

string $password

A password used to identify the connection.

Return Value

bool

If the connection was successful.

Exceptions

MongoConnectionException

protected bool connectUtil()

Connects with a database server

Return Value

bool

If the connection was successful.

Exceptions

MongoConnectionException

array|null lastError()

Check if there was an error on the most recent db operation performed

Return Value

array|null

Returns the error, if there was one, or NULL.

See also

MongoDB::lastError

array prevError()

Checks for the last error thrown during a database operation

Return Value

array

Returns the error and the number of operations ago it occurred.

See also

MongoDB::prevError

array resetError()

Clears any flagged errors on the connection

Return Value

array

Returns the database response.

See also

MongoDB::resetError

bool forceError()

Creates a database error on the database.

Return Value

bool

The database response.

See also

MongoDB::forceError