MongoDB driver classes

Table of Contents

The MongoDB\Driver\Manager class

Introduction

The MongoDB\Driver\Manager is the main entry point to the extension. It is responsible for maintaining connections to MongoDB (be it standalone server, replica set, or sharded cluster).

No connection to MongoDB is made upon instantiating the Manager. This means the MongoDB\Driver\Manager can always be constructed, even though one or more MongoDB servers are down.

Any write or query can throw connection exceptions as connections are created lazily. A MongoDB server may also become unavailable during the life time of the script. It is therefore important that all actions on the Manager to be wrapped in try/catch statements.

Class synopsis

MongoDB\Driver\Manager
final class MongoDB\Driver\Manager {
/* Methods */
final public __construct ([ string $uri = "mongodb://127.0.0.1/ [, array $uriOptions = [] [, array $driverOptions = [] ]]] )
final public MongoDB\Driver\WriteResult executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, MongoDB\Driver\WriteConcern $writeConcern ] )
final public MongoDB\Driver\Cursor executeCommand ( string $db , MongoDB\Driver\Command $command [, MongoDB\Driver\ReadPreference $readPreference ] )
final public MongoDB\Driver\Cursor executeQuery ( string $namespace , MongoDB\Driver\Query $query [, MongoDB\Driver\ReadPreference $readPreference ] )
final public MongoDB\Driver\ReadConcern getReadConcern ( void )
final public MongoDB\Driver\ReadPreference getReadPreference ( void )
final public array getServers ( void )
final public MongoDB\Driver\WriteConcern getWriteConcern ( void )
final public MongoDB\Driver\Server selectServer ( MongoDB\Driver\ReadPreference $readPreference )
}

Examples

Example #1 MongoDB\Driver\Manager::__construct basic example

var_dumping a MongoDB\Driver\Manager will print out various details about the manager that are otherwise not normally exposed. This can be useful to debug how the driver views your MongoDB setup, and which options are used.

<?php

$manager 
= new MongoDB\Driver\Manager("mongodb://localhost:27017");
var_dump($manager);

?>

The above example will output something similar to:

object(MongoDB\Driver\Manager)#1 (3) {
  ["request_id"]=>
  int(1714636915)
  ["uri"]=>
  string(25) "mongodb://localhost:27017"
  ["cluster"]=>
  array(13) {
    ["mode"]=>
    string(6) "direct"
    ["state"]=>
    string(4) "born"
    ["request_id"]=>
    int(0)
    ["sockettimeoutms"]=>
    int(300000)
    ["last_reconnect"]=>
    int(0)
    ["uri"]=>
    string(25) "mongodb://localhost:27017"
    ["requires_auth"]=>
    int(0)
    ["nodes"]=>
    array(...)
    ["max_bson_size"]=>
    int(16777216)
    ["max_msg_size"]=>
    int(50331648)
    ["sec_latency_ms"]=>
    int(15)
    ["peers"]=>
    array(0) {
    }
    ["replSet"]=>
    NULL
  }
}

The MongoDB\Driver\Command class

Introduction

The MongoDB\Driver\Command class is a value object that represents a database command.

To provide Command Helpers the MongoDB\Driver\Command object should be composed.

Class synopsis

MongoDB\Driver\Command
final class MongoDB\Driver\Command {
/* Methods */
final public __construct ( array|object $document )
}

Examples

Example #1 Composing MongoDB\Driver\Command to provide a helper to create collections

<?php
class CreateCollection {
    protected 
$cmd = array();

    function 
__construct($collectionName) {
        
$this->cmd["create"] = (string)$collectionName;
    }
    function 
setAutoIndexId($bool) {
        
$this->cmd["autoIndexId"] = (bool)$bool;
    }
    function 
setCappedCollection($maxBytes$maxDocuments false) {
        
$this->cmd["capped"] = true;
        
$this->cmd["size"]   = (int)$maxBytes;

        if (
$maxDocuments) {
            
$this->cmd["max"] = (int)$maxDocuments;
        }
    }
    function 
usePowerOf2Sizes($bool) {
        if (
$bool) {
            
$this->cmd["flags"] = 1;
        } else {
            
$this->cmd["flags"] = 0;
        }
    }
    function 
setFlags($flags) {
        
$this->cmd["flags"] = (int)$flags;
    }
    function 
getCommand() {
        return new 
MongoDB\Driver\Command($this->cmd);
    }
    function 
getCollectionName() {
        return 
$this->cmd["create"];
    }
}


$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$createCollection = new CreateCollection("cappedCollection");
$createCollection->setCappedCollection(64 1024);

try {
    
$command $createCollection->getCommand();
    
$cursor $manager->executeCommand("databaseName"$command);
    
$response $cursor->toArray()[0];
    
var_dump($response);

    
$collstats = ["collstats" => $createCollection->getCollectionName()];
    
$cursor $manager->executeCommand("databaseName", new MongoDB\Driver\Command($collstats));
    
$response $cursor->toArray()[0];
    
var_dump($response);
} catch(
MongoDB\Driver\Exception $e) {
    echo 
$e->getMessage(), "\n";
    exit;
}

?>

The above example will output:

object(MongoDB\Driver\Command)#3 (1) {
  ["command"]=>
  array(3) {
    ["create"]=>
    string(16) "cappedCollection"
    ["capped"]=>
    bool(true)
    ["size"]=>
    int(65536)
  }
}
array(1) {
  ["ok"]=>
  float(1)
}
array(16) {
  ["ns"]=>
  string(29) "databaseName.cappedCollection"
  ["count"]=>
  int(0)
  ["size"]=>
  int(0)
  ["numExtents"]=>
  int(1)
  ["storageSize"]=>
  int(65536)
  ["nindexes"]=>
  int(1)
  ["lastExtentSize"]=>
  float(65536)
  ["paddingFactor"]=>
  float(1)
  ["paddingFactorNote"]=>
  string(101) "paddingFactor is unused and unmaintained in 2.8. It remains hard coded to 1.0 for compatibility only."
  ["userFlags"]=>
  int(0)
  ["capped"]=>
  bool(true)
  ["max"]=>
  int(9223372036854775807)
  ["maxSize"]=>
  int(65536)
  ["totalIndexSize"]=>
  int(8176)
  ["indexSizes"]=>
  object(stdClass)#4 (1) {
    ["_id_"]=>
    int(8176)
  }
  ["ok"]=>
  float(1)
}

The MongoDB\Driver\Query class

Introduction

The MongoDB\Driver\Query class is a value object that represents a database query.

Class synopsis

MongoDB\Driver\Query
final class MongoDB\Driver\Query {
/* Methods */
final public __construct ( array|object $filter [, array $queryOptions ] )
}

The MongoDB\Driver\BulkWrite class

Introduction

The MongoDB\Driver\BulkWrite collects one or more write operations that should be sent to the server. After adding any number of insert, update, and delete operations, the collection may be executed via MongoDB\Driver\Manager::executeBulkWrite.

Write operations may either be ordered (default) or unordered. Ordered write operations are sent to the server, in the order provided, for serial execution. If a write fails, any remaining operations will be aborted. Unordered operations are sent to the server in an arbitrary order where they may be executed in parallel. Any errors that occur are reported after all operations have been attempted.

Class synopsis

MongoDB\Driver\BulkWrite
final class MongoDB\Driver\BulkWrite implements Countable {
/* Methods */
public __construct ([ array $options ] )
public int count ( void )
public void delete ( array|object $filter [, array $deleteOptions ] )
public mixed insert ( array|object $document )
public void update ( array|object $filter , array|object $newObj [, array $updateOptions ] )
}

Examples

Example #1 Mixed write operations are grouped by type

Mixed write operations (i.e. inserts, updates, and deletes) will be assembled into typed write commands to be sent sequentially to the server.

<?php

$bulk 
= new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert(['_id' => 1'x' => 1]);
$bulk->insert(['_id' => 2'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]]);
$bulk->insert(['_id' => 3'x' => 3]);
$bulk->delete(['x' => 1]);

?>

Will result in four write commands (i.e. roundtrips) being executed. Since the operations are ordered, the third insertion cannot be sent until the preceding update is executed.

Example #2 Ordered write operations causing an error

<?php

$bulk 
= new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete([]);
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3'hello' => 'world']);
$bulk->update(['_id' => 3], ['$set' => ['hello' => 'earth']]);
$bulk->insert(['_id' => 4'hello' => 'pluto']);
$bulk->update(['_id' => 4], ['$set' => ['hello' => 'moon']]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 5]);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY1000);

try {
    
$result $manager->executeBulkWrite('db.collection'$bulk$writeConcern);
} catch (
MongoDB\Driver\Exception\BulkWriteException $e) {
    
$result $e->getWriteResult();

    
// Check if the write concern could not be fulfilled
    
if ($writeConcernError $result->getWriteConcernError()) {
        
printf("%s (%d): %s\n",
            
$writeConcernError->getMessage(),
            
$writeConcernError->getCode(),
            
var_export($writeConcernError->getInfo(), true)
        );
    }

    
// Check if any write operations did not complete at all
    
foreach ($result->getWriteErrors() as $writeError) {
        
printf("Operation#%d: %s (%d)\n",
            
$writeError->getIndex(),
            
$writeError->getMessage(),
            
$writeError->getCode()
        );
    }
} catch (
MongoDB\Driver\Exception\Exception $e) {
    
printf("Other error: %s\n"$e->getMessage());
    exit;
}

printf("Inserted %d document(s)\n"$result->getInsertedCount());
printf("Updated  %d document(s)\n"$result->getModifiedCount());

?>

The above example will output:

Operation#7: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 3 } (11000)
Inserted 4 document(s)
Updated  2 document(s)

If the write concern could not be fullfilled, the example above would output something like:

waiting for replication timed out (64): array (
  'wtimeout' => true,
)
Operation#7: E11000 duplicate key error index: databaseName.collectionName.$_id_ dup key: { : 3 } (11000)
Inserted 4 document(s)
Updated  2 document(s)

If we execute the example above, but allow for unordered writes:

<?php

$bulk 
= new MongoDB\Driver\BulkWrite(['ordered' => false]);
/* ... */

?>

The above example will output:

Operation#7: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 3 } (11000)
Operation#8: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 4 } (11000)
Inserted 5 document(s)
Updated  2 document(s)

See Also

  • MongoDB\Driver\Manager::executeBulkWrite
  • MongoDB\Driver\WriteResult
  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\WriteConcernError
  • MongoDB\Driver\WriteError

The MongoDB\Driver\WriteConcern class

Introduction

MongoDB\Driver\WriteConcern describes the level of acknowledgement requested from MongoDB for write operations to a standalone mongod or to replica sets or to sharded clusters. In sharded clusters, mongos instances will pass the write concern on to the shards.

Class synopsis

MongoDB\Driver\WriteConcern
final class MongoDB\Driver\WriteConcern implements MongoDB\BSON\Serializable {
/* Constants */
const string MongoDB\Driver\WriteConcern::MAJORITY = "majority" ;
/* Methods */
final public object bsonSerialize ( void )
final public __construct ( string|int $w [, integer $wtimeout [, boolean $journal ]] )
final public bool|null getJournal ( void )
final public string|int|null getW ( void )
final public int getWtimeout ( void )
}

Predefined Constants

MongoDB\Driver\WriteConcern::MAJORITY

Majority of all the members in the set; arbiters, non-voting members, passive members, hidden members and delayed members are all included in the definition of majority write concern.

The MongoDB\Driver\ReadPreference class

Introduction

Class synopsis

MongoDB\Driver\ReadPreference
final class MongoDB\Driver\ReadPreference implements MongoDB\BSON\Serializable {
/* Constants */
const integer MongoDB\Driver\ReadPreference::RP_PRIMARY = 1 ;
const integer MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED = 5 ;
const integer MongoDB\Driver\ReadPreference::RP_SECONDARY = 2 ;
const integer MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED = 6 ;
const integer MongoDB\Driver\ReadPreference::RP_NEAREST = 10 ;
const integer MongoDB\Driver\ReadPreference::NO_MAX_STALENESS = -1 ;
const integer MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS = 90 ;
/* Methods */
final public object bsonSerialize ( void )
final public __construct ( int $mode [, array $tagSets = NULL [, array $options = [] ]] )
final public integer getMaxStalenessSeconds ( void )
final public integer getMode ( void )
final public array getTagSets ( void )
}

Predefined Constants

MongoDB\Driver\ReadPreference::RP_PRIMARY

All operations read from the current replica set primary. This is the default read preference for MongoDB.

MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED

In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.

MongoDB\Driver\ReadPreference::RP_SECONDARY

All operations read from the secondary members of the replica set.

MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED

In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.

MongoDB\Driver\ReadPreference::RP_NEAREST

Operations read from member of the replica set with the least network latency, irrespective of the member's type.

MongoDB\Driver\ReadPreference::NO_MAX_STALENESS

The default value for the "maxStalenessSeconds" option is to specify no limit on maximum staleness, which means that the driver will not consider a secondary's lag when choosing where to direct a read operation.

MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS

The minimum value for the "maxStalenessSeconds" option is 90 seconds. The driver estimates secondaries' staleness by periodically checking the latest write date of each replica set member. Since these checks are infrequent, the staleness estimate is coarse. Thus, the driver cannot enforce a max staleness value of less than 90 seconds.

Changelog

Version Description
1.2.0 Added the MongoDB\Driver\ReadPreference::NO_MAX_STALENESS and MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS constants.

The MongoDB\Driver\ReadConcern class

Introduction

MongoDB\Driver\ReadConcern controls the level of isolation for read operations for replica sets and replica set shards. This option requires the WiredTiger storage engine and MongoDB 3.2 or later.

Class synopsis

MongoDB\Driver\ReadConcern
final class MongoDB\Driver\ReadConcern implements MongoDB\BSON\Serializable {
/* Constants */
const string MongoDB\Driver\ReadConcern::LINEARIZABLE = "linearizable" ;
const string MongoDB\Driver\ReadConcern::LOCAL = "local" ;
const string MongoDB\Driver\ReadConcern::MAJORITY = "majority" ;
/* Methods */
final public object bsonSerialize ( void )
final public __construct ([ string $level ] )
final public string|null getLevel ( void )
}

Predefined Constants

MongoDB\Driver\ReadConcern::LINEARIZABLE

A linearizable read avoids returning reads from a stale primary (one that has already been superseded by a new primary but doesn't know it yet). It is important to note that this read concern level does not by itself produce linearizable reads; they must be issued in conjunction with MongoDB\Driver\WriteConcern::MAJORITY writes to the same document(s) in order to be linearizable.

MongoDB\Driver\ReadConcern::LOCAL

Queries using this read concern will return the node's most recent copy of the data. This provides no guarantee that the data has been written to a majority of the nodes (i.e. it may be rolled back).

This is the default read concern level.

MongoDB\Driver\ReadConcern::MAJORITY

Queries using this read concern will return the node's most recent copy of the data confirmed as having been written to a majority of the nodes (i.e. the data cannot be rolled back).

Changelog

Version Description
1.2.0 Added the MongoDB\Driver\ReadConcern::LINEARIZABLE constant.

The MongoDB\Driver\Cursor class

Introduction

The MongoDB\Driver\Cursor class encapsulates the results of a MongoDB command or query and may be returned by MongoDB\Driver\Manager::executeCommand or MongoDB\Driver\Manager::executeQuery, respectively.

Class synopsis

MongoDB\Driver\Cursor
class MongoDB\Driver\Cursor implements Traversable {
/* Methods */
final private __construct ( void )
final public MongoDB\Driver\CursorId getId ( void )
final public MongoDB\Driver\Server getServer ( void )
final public bool isDead ( void )
final public void setTypeMap ( array $typemap )
final public array toArray ( void )
}

The MongoDB\Driver\CursorId class

Introduction

Class synopsis

MongoDB\Driver\CursorId
final class MongoDB\Driver\CursorId {
/* Methods */
final private __construct ( void )
final public string __toString ( void )
}

The MongoDB\Driver\Server class

Introduction

Class synopsis

MongoDB\Driver\Server
final class MongoDB\Driver\Server {
/* Constants */
const integer MongoDB\Driver\Server::TYPE_UNKNOWN = 0 ;
const integer MongoDB\Driver\Server::TYPE_STANDALONE = 1 ;
const integer MongoDB\Driver\Server::TYPE_MONGOS = 2 ;
const integer MongoDB\Driver\Server::TYPE_POSSIBLE_PRIMARY = 3 ;
const integer MongoDB\Driver\Server::TYPE_RS_PRIMARY = 4 ;
const integer MongoDB\Driver\Server::TYPE_RS_SECONDARY = 5 ;
const integer MongoDB\Driver\Server::TYPE_RS_ARBITER = 6 ;
const integer MongoDB\Driver\Server::TYPE_RS_OTHER = 7 ;
const integer MongoDB\Driver\Server::TYPE_RS_GHOST = 8 ;
/* Methods */
final private __construct ( void )
final public MongoDB\Driver\WriteResult executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, MongoDB\Driver\WriteConcern $writeConcern ] )
final public MongoDB\Driver\Cursor executeCommand ( string $db , MongoDB\Driver\Command $command [, MongoDB\Driver\ReadPreference $readPreference ] )
final public MongoDB\Driver\Cursor executeQuery ( string $namespace , MongoDB\Driver\Query $query [, MongoDB\Driver\ReadPreference $readPreference ] )
final public string getHost ( void )
final public array getInfo ( void )
final public string getLatency ( void )
final public int getPort ( void )
final public array getTags ( void )
final public int getType ( void )
final public bool isArbiter ( void )
final public bool isHidden ( void )
final public bool isPassive ( void )
final public bool isPrimary ( void )
final public bool isSecondary ( void )
}

Predefined Constants

MongoDB\Driver\Server::TYPE_UNKNOWN

Unknown server type, returned by MongoDB\Driver\Server::getType.

MongoDB\Driver\Server::TYPE_STANDALONE

Standalone server type, returned by MongoDB\Driver\Server::getType.

MongoDB\Driver\Server::TYPE_MONGOS

Mongos server type, returned by MongoDB\Driver\Server::getType.

MongoDB\Driver\Server::TYPE_POSSIBLE_PRIMARY

Replica set possible primary server type, returned by MongoDB\Driver\Server::getType.

A server may be identified as a possible primary if it has not yet been checked but another memory of the replica set thinks it is the primary.

MongoDB\Driver\Server::TYPE_RS_PRIMARY

Replica set primary server type, returned by MongoDB\Driver\Server::getType.

MongoDB\Driver\Server::TYPE_RS_SECONDARY

Replica set secondary server type, returned by MongoDB\Driver\Server::getType.

MongoDB\Driver\Server::TYPE_RS_ARBITER

Replica set arbiter server type, returned by MongoDB\Driver\Server::getType.

MongoDB\Driver\Server::TYPE_RS_OTHER

Replica set other server type, returned by MongoDB\Driver\Server::getType.

Such servers may be hidden, starting up, or recovering. They cannot be queried, but their hosts lists are useful for discovering the current replica set configuration.

MongoDB\Driver\Server::TYPE_RS_GHOST

Replica set ghost server type, returned by MongoDB\Driver\Server::getType.

Servers may be identified as such in at least three situations: briefly during server startup; in an uninitialized replica set; or when the server is shunned (i.e. removed from the replica set config). They cannot be queried, nor can their host list be used to discover the current replica set configuration; however, the client may monitor this server in hope that it transitions to a more useful state.

The MongoDB\Driver\WriteConcernError class

Introduction

The MongoDB\Driver\WriteConcernError class encapsulates information about a write concern error and may be returned by MongoDB\Driver\WriteResult::getWriteConcernError.

Class synopsis

MongoDB\Driver\WriteConcernError
final class MongoDB\Driver\WriteConcernError {
/* Methods */
final public int getCode ( void )
final public mixed getInfo ( void )
final public string getMessage ( void )
}

The MongoDB\Driver\WriteError class

Introduction

The MongoDB\Driver\WriteError class encapsulates information about a write error and may be returned as an array element from MongoDB\Driver\WriteResult::getWriteErrors.

Class synopsis

MongoDB\Driver\WriteError
final class MongoDB\Driver\WriteError {
/* Methods */
final public int getCode ( void )
final public int getIndex ( void )
final public mixed getInfo ( void )
final public string getMessage ( void )
}

The MongoDB\Driver\WriteResult class

Introduction

The MongoDB\Driver\WriteResult class encapsulates information about an executed MongoDB\Driver\BulkWrite and may be returned by MongoDB\Driver\Manager::executeBulkWrite.

Class synopsis

MongoDB\Driver\WriteResult
final class MongoDB\Driver\WriteResult {
/* Methods */
final public int|null getDeletedCount ( void )
final public int|null getInsertedCount ( void )
final public int|null getMatchedCount ( void )
final public int|null getModifiedCount ( void )
final public MongoDB\Driver\Server getServer ( void )
final public int|null getUpsertedCount ( void )
final public array getUpsertedIds ( void )
final public MongoDB\Driver\WriteConcernError|null getWriteConcernError ( void )
final public array getWriteErrors ( void )
final public bool isAcknowledged ( void )
}