MongoDB driver classes

目次

The MongoDB\Driver\Manager class

はじめに

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.

クラス概要

MongoDB\Driver\Manager
final class MongoDB\Driver\Manager {
/* メソッド */
final public void addSubscriber(MongoDB\Driver\Monitoring\Subscriber $subscriber)
final public __construct(stringnull $uri = null, arraynull $uriOptions = null, arraynull $driverOptions = null)
final public MongoDB\Driver\ClientEncryption createClientEncryption(array $options)
final public MongoDB\Driver\WriteResult executeBulkWrite(string $namespace, MongoDB\Driver\BulkWrite $bulk, arrayMongoDB\Driver\WriteConcernnull $options = null)
final public MongoDB\Driver\Cursor executeCommand(string $db, MongoDB\Driver\Command $command, arrayMongoDB\Driver\ReadPreferencenull $options = null)
final public MongoDB\Driver\Cursor executeQuery(string $namespace, MongoDB\Driver\Query $query, arrayMongoDB\Driver\ReadPreferencenull $options = null)
final public MongoDB\Driver\Cursor executeReadCommand(string $db, MongoDB\Driver\Command $command, arraynull $options = null)
final public MongoDB\Driver\Cursor executeReadWriteCommand(string $db, MongoDB\Driver\Command $command, arraynull $options = null)
final public MongoDB\Driver\Cursor executeWriteCommand(string $db, MongoDB\Driver\Command $command, arraynull $options = null)
final public arrayobjectnull getEncryptedFieldsMap()
final public MongoDB\Driver\ReadConcern getReadConcern()
final public MongoDB\Driver\ReadPreference getReadPreference()
final public array getServers()
final public MongoDB\Driver\WriteConcern getWriteConcern()
final public void removeSubscriber(MongoDB\Driver\Monitoring\Subscriber $subscriber)
final public MongoDB\Driver\Server selectServer(MongoDB\Driver\ReadPreferencenull $readPreference = null)
final public MongoDB\Driver\Session startSession(arraynull $options = null)
}

例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);

?>

上の例の出力は、 たとえば以下のようになります。

object(MongoDB\Driver\Manager)#1 (2) {
  ["uri"]=>
  string(26) "mongodb://127.0.0.1:27017/"
  ["cluster"]=>
  array(0) {
  }
}

The MongoDB\Driver\Command class

はじめに

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.

クラス概要

MongoDB\Driver\Command
final class MongoDB\Driver\Command {
/* メソッド */
final public __construct(arrayobject $document, arraynull $commandOptions = null)
}

例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 
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;
}

?>

上の例の出力は以下となります。

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

はじめに

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

クラス概要

MongoDB\Driver\Query
final class MongoDB\Driver\Query {
/* メソッド */
final public __construct(arrayobject $filter, arraynull $queryOptions = null)
}

The MongoDB\Driver\BulkWrite class

はじめに

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.

クラス概要

MongoDB\Driver\BulkWrite
final class MongoDB\Driver\BulkWrite implements Countable {
/* メソッド */
public __construct(arraynull $options = null)
public int count()
public void delete(arrayobject $filter, arraynull $deleteOptions = null)
public mixed insert(arrayobject $document)
public void update(arrayobject $filter, arrayobject $newObj, arraynull $updateOptions = null)
}

例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.

例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());

?>

上の例の出力は以下となります。

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]);
/* ... */

?>

上の例の出力は以下となります。

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)

参考

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

The MongoDB\Driver\Session class

はじめに

The MongoDB\Driver\Session class represents a client session and is returned by MongoDB\Driver\Manager::startSession. Commands, queries, and write operations may then be associated the session.

クラス概要

MongoDB\Driver\Session
final class MongoDB\Driver\Session {
/* 定数 */
const string MongoDB\Driver\Session::TRANSACTION_NONE = none;
const string MongoDB\Driver\Session::TRANSACTION_STARTING = starting;
const string MongoDB\Driver\Session::TRANSACTION_IN_PROGRESS = in_progress;
const string MongoDB\Driver\Session::TRANSACTION_COMMITTED = committed;
const string MongoDB\Driver\Session::TRANSACTION_ABORTED = aborted;
/* メソッド */
final public void abortTransaction()
final public void advanceClusterTime(arrayobject $clusterTime)
final public void advanceOperationTime(MongoDB\BSON\TimestampInterface $operationTime)
final public void commitTransaction()
final private __construct()
final public void endSession()
final public objectnull getClusterTime()
final public object getLogicalSessionId()
final public MongoDB\BSON\Timestampnull getOperationTime()
final public MongoDB\Driver\Servernull getServer()
final public arraynull getTransactionOptions()
final public string getTransactionState()
final public bool isDirty()
final public bool isInTransaction()
final public void startTransaction(arraynull $options = null)
}

定義済み定数

MongoDB\Driver\Session::TRANSACTION_NONE

There is no transaction in progress.

MongoDB\Driver\Session::TRANSACTION_STARTING

A transaction has been started, but no operation has been sent to the server.

MongoDB\Driver\Session::TRANSACTION_IN_PROGRESS

A transaction is in progress.

MongoDB\Driver\Session::TRANSACTION_COMMITTED

The transaction was committed.

MongoDB\Driver\Session::TRANSACTION_ABORTED

The transaction was aborted.

The MongoDB\Driver\ClientEncryption class

はじめに

The MongoDB\Driver\ClientEncryption class handles creation of data keys for client-side encryption, as well as manually encrypting and decrypting values.

クラス概要

MongoDB\Driver\ClientEncryption
final class MongoDB\Driver\ClientEncryption {
/* 定数 */
const string MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC = AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic;
const string MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM = AEAD_AES_256_CBC_HMAC_SHA_512-Random;
const string MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED = Indexed;
const string MongoDB\Driver\ClientEncryption::ALGORITHM_UNINDEXED = Unindexed;
const string MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW = RangePreview;
const string MongoDB\Driver\ClientEncryption::QUERY_TYPE_EQUALITY = equality;
const string MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE_PREVIEW = rangePreview;
/* メソッド */
final public objectnull addKeyAltName(MongoDB\BSON\Binary $keyId, string $keyAltName)
final public __construct(array $options)
final public MongoDB\BSON\Binary createDataKey(string $kmsProvider, arraynull $options = null)
final public mixed decrypt(MongoDB\BSON\Binary $value)
final public object deleteKey(MongoDB\BSON\Binary $keyId)
final public MongoDB\BSON\Binary encrypt(mixed $value, arraynull $options = null)
final public object encryptExpression(arrayobject $expr, arraynull $options = null)
final public objectnull getKey(MongoDB\BSON\Binary $keyId)
final public objectnull getKeyByAltName(string $keyAltName)
final public MongoDB\Driver\Cursor getKeys()
final public objectnull removeKeyAltName(MongoDB\BSON\Binary $keyId, string $keyAltName)
final public object rewrapManyDataKey(arrayobject $filter, arraynull $options = null)
}

定義済み定数

MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC

Specifies an algorithm for » deterministic encryption, which is suitable for querying.

MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM

Specifies an algorithm for » randomized encryption

MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED

Specifies an algorithm for an indexed, encrypted payload, which can be used with queryable encryption.

To insert or query with an indexed, encrypted payload, the MongoDB\Driver\Manager must be configured with the "autoEncryption" driver option. The "bypassQueryAnalysis" auto encryption option may be true. The "bypassAutoEncryption" auto encryption option must be false.

MongoDB\Driver\ClientEncryption::ALGORITHM_UNINDEXED

Specifies an algorithm for an unindexed, encrypted payload.

MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW

Specifies an algorithm for a range, encrypted payload, which can be used with queryable encryption.

To query with a range encrypted payload, the MongoDB\Driver\Manager must be configured with the "autoEncryption" driver option. The "bypassQueryAnalysis" auto encryption option may be true. The "bypassAutoEncryption" auto encryption option must be false.

注意:

The range algorithm is experimental only. It is not intended for public use.

The PHP driver does not yet support range queries for decimal128 BSON field types.

MongoDB\Driver\ClientEncryption::QUERY_TYPE_EQUALITY

Specifies an equality query type, which is used in conjunction with MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED.

MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE_PREVIEW

Specifies a range query type, which is used in conjunction with MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW.

変更履歴

バージョン 説明
PECL mongodb 1.16.0 Added MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW and MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE_PREVIEW.
PECL mongodb 1.14.0 Added MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED, MongoDB\Driver\ClientEncryption::ALGORITHM_UNINDEXED, and MongoDB\Driver\ClientEncryption::QUERY_TYPE_EQUALITY

参考

  • MongoDB\Driver\Manager::createClientEncryption

The MongoDB\Driver\ServerApi class

はじめに

クラス概要

MongoDB\Driver\ServerApi
final class MongoDB\Driver\ServerApi implements MongoDB\BSON\Serializable, Serializable {
/* 定数 */
const string MongoDB\Driver\ServerAPI::V1 = "1";
/* メソッド */
final public stdClass bsonSerialize()
final public __construct(string $version, boolnull $strict = null, boolnull $deprecationErrors = null)
final public string serialize()
final public void unserialize(string $data)
}

定義済み定数

MongoDB\Driver\ServerApi::V1

Server API version 1.

例1 Declare an API version on a manager

<?php

use MongoDB\Driver\Manager;
use 
MongoDB\Driver\ServerApi;

$v1 = new ServerApi(ServerApi::v1);
$manager = new Manager('mongodb://localhost:27017', [], ['serverApi' => $v1]);

$command = new MongoDB\Driver\Command(['buildInfo' => 1]);

try {
    
$cursor $manager->executeCommand('admin'$command);
} catch(
MongoDB\Driver\Exception $e) {
    echo 
$e->getMessage(), "\n";
    exit;
}

/* The buildInfo command returns a single result document, so we need to access
 * the first result in the cursor. */
$buildInfo $cursor->toArray()[0];

echo 
$buildInfo->version"\n";

?>

上の例の出力は以下となります。

4.9.0-alpha7-49-gb968ca0

例2 Declare a strict API version on a manager

The following example sets the strict flag, which tells the server to reject any command that is not part of the declared API version. This results in an error when running the buildInfo command.

<?php

use MongoDB\Driver\Manager;
use 
MongoDB\Driver\ServerApi;

$v1 = new ServerApi(ServerApi::v1true);
$manager = new Manager('mongodb://localhost:27017', [], ['serverApi' => $v1]);

$command = new MongoDB\Driver\Command(['buildInfo' => 1]);

try {
    
$cursor $manager->executeCommand('admin'$command);
} catch(
MongoDB\Driver\Exception $e) {
    echo 
$e->getMessage(), "\n";
    exit;
}

/* The buildInfo command returns a single result document, so we need to access
 * the first result in the cursor. */
$buildInfo $cursor->toArray()[0];

echo 
$buildInfo->version"\n";

?>

上の例の出力は以下となります。

Provided apiStrict:true, but the command buildInfo is not in API Version 1

The MongoDB\Driver\WriteConcern class

はじめに

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.

クラス概要

MongoDB\Driver\WriteConcern
final class MongoDB\Driver\WriteConcern implements MongoDB\BSON\Serializable, Serializable {
/* 定数 */
const string MongoDB\Driver\WriteConcern::MAJORITY = "majority";
/* メソッド */
final public stdClass bsonSerialize()
final public __construct(stringint $w, intnull $wtimeout = null, boolnull $journal = null)
final public boolnull getJournal()
final public stringintnull getW()
final public int getWtimeout()
final public bool isDefault()
final public string serialize()
final public void unserialize(string $data)
}

定義済み定数

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.

変更履歴

バージョン 説明
PECL mongodb 1.7.0 Implements Serializable.
PECL mongodb 1.2.0 Implements MongoDB\BSON\Serializable.

The MongoDB\Driver\ReadPreference class

はじめに

クラス概要

MongoDB\Driver\ReadPreference
final class MongoDB\Driver\ReadPreference implements MongoDB\BSON\Serializable, Serializable {
/* 定数 */
const int MongoDB\Driver\ReadPreference::RP_PRIMARY = 1;
const int MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED = 5;
const int MongoDB\Driver\ReadPreference::RP_SECONDARY = 2;
const int MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED = 6;
const int MongoDB\Driver\ReadPreference::RP_NEAREST = 10;
const string MongoDB\Driver\ReadPreference::PRIMARY = primary;
const string MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED = primaryPreferred;
const string MongoDB\Driver\ReadPreference::SECONDARY = secondary;
const string MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED = secondaryPreferred;
const string MongoDB\Driver\ReadPreference::NEAREST = nearest;
const int MongoDB\Driver\ReadPreference::NO_MAX_STALENESS = -1;
const int MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS = 90;
/* メソッド */
final public stdClass bsonSerialize()
final public __construct(stringint $mode, arraynull $tagSets = null, arraynull $options = null)
final public objectnull getHedge()
final public int getMaxStalenessSeconds()
final public int getMode()
final public string getModeString()
final public array getTagSets()
final public string serialize()
final public void unserialize(string $data)
}

定義済み定数

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::PRIMARY

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

MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED

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

MongoDB\Driver\ReadPreference::SECONDARY

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

MongoDB\Driver\ReadPreference::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::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.

変更履歴

バージョン 説明
PECL mongodb 1.7.0

Added the MongoDB\Driver\ReadPreference::PRIMARY, MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED, MongoDB\Driver\ReadPreference::SECONDARY, MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED, MongoDB\Driver\ReadPreference::NEAREST constants.

Implements Serializable.

PECL mongodb 1.2.0

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

Implements MongoDB\BSON\Serializable.

The MongoDB\Driver\ReadConcern class

はじめに

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

クラス概要

MongoDB\Driver\ReadConcern
final class MongoDB\Driver\ReadConcern implements MongoDB\BSON\Serializable, Serializable {
/* 定数 */
const string MongoDB\Driver\ReadConcern::AVAILABLE = "available";
const string MongoDB\Driver\ReadConcern::LINEARIZABLE = "linearizable";
const string MongoDB\Driver\ReadConcern::LOCAL = "local";
const string MongoDB\Driver\ReadConcern::MAJORITY = "majority";
const string MongoDB\Driver\ReadConcern::SNAPSHOT = "snapshot";
/* メソッド */
final public stdClass bsonSerialize()
final public __construct(stringnull $level = null)
final public stringnull getLevel()
final public bool isDefault()
final public string serialize()
final public void unserialize(string $data)
}

定義済み定数

MongoDB\Driver\ReadConcern::AVAILABLE

Default for reads against secondaries when afterClusterTimeand level are unspecified.

The query returns the instance's most recent data. Provides no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).

For unsharded collections (including collections in a standalone deployment or a replica set deployment), "local" and "available" read concerns behave identically.

For a sharded cluster, "available" read concern provides greater tolerance for partitions since it does not wait to ensure consistency guarantees. However, a query with "available" read concern may return orphan documents if the shard is undergoing chunk migrations since the "available" read concern, unlike "local" read concern, does not contact the shard's primary nor the config servers for updated metadata.

MongoDB\Driver\ReadConcern::LINEARIZABLE

The query returns data that reflects all successful writes issued with a write concern of "majority" and acknowledged prior to the start of the read operation. For replica sets that run with writeConcernMajorityJournalDefault set to true, linearizable read concern returns data that will never be rolled back.

With writeConcernMajorityJournalDefault set to false, MongoDB will not wait for w: "majority" writes to be durable before acknowledging the writes. As such, "majority" write operations could possibly roll back in the event of a loss of a replica set member.

You can specify linearizable read concern for read operations on the primary only.

Linearizable read concern guarantees only apply if read operations specify a query filter that uniquely identifies a single document.

ヒント

Always use maxTimeMS with linearizable read concern in case a majority of data bearing members are unavailable. maxTimeMS ensures that the operation does not block indefinitely and instead ensures that the operation returns an error if the read concern cannot be fulfilled.

Linearizable read concern requires MongoDB 3.4.

MongoDB\Driver\ReadConcern::LOCAL

Default for reads against primary if level is unspecified and for reads against secondaries if level is unspecified but afterClusterTime is specified.

The query returns the instance's most recent data. Provides no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).

MongoDB\Driver\ReadConcern::MAJORITY

The query returns the instance's most recent data acknowledged as having been written to a majority of members in the replica set.

To use read concern level of "majority", replica sets must use WiredTiger storage engine and election protocol version 1.

MongoDB\Driver\ReadConcern::SNAPSHOT

Read concern "snapshot" is available for multi-document transactions, and starting in MongoDB 5.0, certain read operations outside of multi-document transactions.

If the transaction is not part of a causally consistent session, upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data.

If the transaction is part of a causally consistent session, upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data that provides causal consistency with the operation immediately preceding the transaction start.

Outside of multi-document transactions, read concern "snapshot" is available on primaries and secondaries for the following read operations: find, aggregate, and distinct (on unsharded collections). All other read commands prohibit "snapshot".

変更履歴

バージョン 説明
PECL mongodb 1.11.0

Added the MongoDB\Driver\ReadConcern::SNAPSHOT constant.

PECL mongodb 1.7.0 Implements Serializable.
PECL mongodb 1.4.0

Added the MongoDB\Driver\ReadConcern::AVAILABLE constant.

PECL mongodb 1.2.0

Added the MongoDB\Driver\ReadConcern::LINEARIZABLE constant.

Implements MongoDB\BSON\Serializable.

The MongoDB\Driver\Cursor class

はじめに

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.

クラス概要

MongoDB\Driver\Cursor
final class MongoDB\Driver\Cursor implements MongoDB\Driver\CursorInterface, Iterator {
/* メソッド */
final private __construct()
public arrayobjectnull current()
final public MongoDB\Driver\CursorId getId()
final public MongoDB\Driver\Server getServer()
final public bool isDead()
public int key()
public void next()
public void rewind()
final public void setTypeMap(array $typemap)
final public array toArray()
public bool valid()
}

変更履歴

バージョン 説明
PECL mongodb 1.9.0 Implements Iterator.
PECL mongodb 1.6.0 Implements MongoDB\Driver\CursorInterface, which extends Traversable.

例1 Reading a result set

MongoDB\Driver\Manager::executeCommand and MongoDB\Driver\Manager::executeQuery both return their result(s) as a MongoDB\Driver\Cursor object. This object can be used to iterate over the result set of the command or query.

Because MongoDB\Driver\Cursor implements the Traversable interface, you can simply iterate over the result set with foreach.

<?php

$manager 
= new MongoDB\Driver\Manager();

/* Insert some documents so that our query returns information */
$bulkWrite = new MongoDB\Driver\BulkWrite;
$bulkWrite->insert(['name' => 'Ceres''size' => 946'distance' => 2.766]);
$bulkWrite->insert(['name' => 'Vesta''size' => 525'distance' => 2.362]);
$manager->executeBulkWrite("test.asteroids"$bulkWrite);

/* Query for all the items in the collection */
$query = new MongoDB\Driver\Query( [] );

/* Query the "asteroids" collection of the "test" database */
$cursor $manager->executeQuery("test.asteroids"$query);

/* $cursor now contains an object that wraps around the result set. Use
 * foreach() to iterate over all the result */
foreach($cursor as $document) {
    
print_r($document);
}

?>

上の例の出力は、 たとえば以下のようになります。

stdClass Object
(
    [_id] => MongoDB\BSON\ObjectId Object
        (
            [oid] => 5a4cff2f122d3321565d8cc2
        )

    [name] => Ceres
    [size] => 946
    [distance] => 2.766
)
stdClass Object
(
    [_id] => MongoDB\BSON\ObjectId Object
        (
            [oid] => 5a4cff2f122d3321565d8cc3
        )

    [name] => Vesta
    [size] => 525
    [distance] => 2.362
}

例2 Reading a result set for a tailable cursor

» Tailable cursors are a special type of MongoDB cursor that allows the client to read some results and then wait until more documents become available. These cursors are primarily used with » Capped Collections and » Change Streams.

While normal cursors can be iterated once with foreach, that approach will not work with tailable cursors. When foreach is used with a tailable cursor, the loop will stop upon reaching the end of the initial result set. Attempting to continue iteration on the cursor with a second foreach would throw an exception, since PHP attempts to rewind the cursor. Similar to result objects in other database drivers, cursors in MongoDB only support forward iteration, which means they cannot be rewound.

In order to continuously read from a tailable cursor, the Cursor object must be wrapped with an IteratorIterator. This allows the application to directly control the cursor's iteration, avoid inadvertently rewinding the cursor, and decide when to wait for new results or stop iteration entirely.

In order to demonstrate a tailable cursor in action, two scripts will be used: a "producer" and a "consumer". The producer script will create a new capped collection using the » create command and proceed to insert a new document into that collection each second.

<?php

$manager 
= new MongoDB\Driver\Manager;

$manager->executeCommand('test', new MongoDB\Driver\Command([
    
'create' => 'asteroids',
    
'capped' => true,
    
'size' => 1048576,
]));

while (
true) {
    
$bulkWrite = new MongoDB\Driver\BulkWrite;
    
$bulkWrite->insert(['createdAt' => new MongoDB\BSON\UTCDateTime]);
    
$manager->executeBulkWrite('test.asteroids'$bulkWrite);

    
sleep(1);
}

?>

With the producer script still running, a second consumer script may be executed to read the inserted documents using a tailable cursor, indicated by the tailable and awaitData options to MongoDB\Driver\Query::__construct.

<?php

$manager 
= new MongoDB\Driver\Manager;

$query = new MongoDB\Driver\Query([], [
    
'tailable' => true,
    
'awaitData' => true,
]);

$cursor $manager->executeQuery('test.asteroids'$query);

$iterator = new IteratorIterator($cursor);

$iterator->rewind();

while (
true) {
    if (
$iterator->valid()) {
        
$document $iterator->current();
        
printf("Consumed document created at: %s\n"$document->createdAt);
    }

    
$iterator->next();
}

?>

The consumer script will start by quickly printing all available documents in the capped collection (as if foreach had been used); however, it will not terminate upon reaching the end of the initial result set. Since the cursor is tailable, calling IteratorIterator::next will block and wait for additional results. IteratorIterator::valid is also used to check if there is actually data available to read at each step.

注意: This example uses the awaitData query option to instruct the server to block for a short period (e.g. one second) at the end of the result set before returning a response to the driver. This is used to prevent the driver from aggressively polling the server when there are no results available. The maxAwaitTimeMS option may be used in conjunction with tailable and awaitData to specify the amount of time that the server should block when it reaches the end of the result set.

エラー / 例外

When iterating over the cursor object, BSON data is converted into PHP variables. This iteration can cause the following Exceptions:

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

The MongoDB\Driver\CursorId class

はじめに

The MongoDB\Driver\CursorID class is a value object that represents a cursor ID. Instances of this class are returned by MongoDB\Driver\Cursor::getId.

クラス概要

MongoDB\Driver\CursorId
final class MongoDB\Driver\CursorId implements Serializable, Stringable {
/* メソッド */
final private __construct()
final public string serialize()
final public string __toString()
final public void unserialize(string $data)
}

変更履歴

バージョン 説明
PECL mongodb 1.12.0 Implements Stringable for PHP 8.0+.
PECL mongodb 1.7.0 Implements Serializable.

The MongoDB\Driver\CursorInterface interface

はじめに

This interface is implemented by MongoDB\Driver\Cursor to be used as a parameter, return, or property type in userland classes.

クラス概要

MongoDB\Driver\CursorInterface
class MongoDB\Driver\CursorInterface implements Traversable {
/* メソッド */
abstract public MongoDB\Driver\CursorId getId()
abstract public MongoDB\Driver\Server getServer()
abstract public bool isDead()
abstract public void setTypeMap(array $typemap)
abstract public array toArray()
}

変更履歴

バージョン 説明
PECL mongodb 1.15.0 Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

The MongoDB\Driver\Server class

はじめに

クラス概要

MongoDB\Driver\Server
final class MongoDB\Driver\Server {
/* 定数 */
const int MongoDB\Driver\Server::TYPE_UNKNOWN = 0;
const int MongoDB\Driver\Server::TYPE_STANDALONE = 1;
const int MongoDB\Driver\Server::TYPE_MONGOS = 2;
const int MongoDB\Driver\Server::TYPE_POSSIBLE_PRIMARY = 3;
const int MongoDB\Driver\Server::TYPE_RS_PRIMARY = 4;
const int MongoDB\Driver\Server::TYPE_RS_SECONDARY = 5;
const int MongoDB\Driver\Server::TYPE_RS_ARBITER = 6;
const int MongoDB\Driver\Server::TYPE_RS_OTHER = 7;
const int MongoDB\Driver\Server::TYPE_RS_GHOST = 8;
const int MongoDB\Driver\Server::TYPE_LOAD_BALANCER = 9;
/* メソッド */
final private __construct()
final public MongoDB\Driver\WriteResult executeBulkWrite(string $namespace, MongoDB\Driver\BulkWrite $bulk, arrayMongoDB\Driver\WriteConcernnull $options = null)
final public MongoDB\Driver\Cursor executeCommand(string $db, MongoDB\Driver\Command $command, arrayMongoDB\Driver\ReadPreferencenull $options = null)
final public MongoDB\Driver\Cursor executeQuery(string $namespace, MongoDB\Driver\Query $query, arrayMongoDB\Driver\ReadPreferencenull $options = null)
final public MongoDB\Driver\Cursor executeReadCommand(string $db, MongoDB\Driver\Command $command, arraynull $options = null)
final public MongoDB\Driver\Cursor executeReadWriteCommand(string $db, MongoDB\Driver\Command $command, arraynull $options = null)
final public MongoDB\Driver\Cursor executeWriteCommand(string $db, MongoDB\Driver\Command $command, arraynull $options = null)
final public string getHost()
final public array getInfo()
final public integernull getLatency()
final public int getPort()
final public MongoDB\Driver\ServerDescription getServerDescription()
final public array getTags()
final public int getType()
final public bool isArbiter()
final public bool isHidden()
final public bool isPassive()
final public bool isPrimary()
final public bool isSecondary()
}

定義済み定数

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.

MongoDB\Driver\Server::TYPE_LOAD_BALANCER

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

変更履歴

バージョン 説明
PECL mongodb 1.11.0

Added the MongoDB\Driver\Server::TYPE_LOAD_BALANCER constant.

The MongoDB\Driver\ServerDescription class

はじめに

The MongoDB\Driver\ServerDescription class is a value object that represents a server to which the driver is connected. Instances of this class are returned by MongoDB\Driver\Server::getServerDescription and MongoDB\Driver\Monitoring\ServerChangedEvent methods.

クラス概要

MongoDB\Driver\ServerDescription
final class MongoDB\Driver\ServerDescription {
/* 定数 */
const string MongoDB\Driver\ServerDescription::TYPE_UNKNOWN = "Unknown";
const string MongoDB\Driver\ServerDescription::TYPE_STANDALONE = "Standalone";
const string MongoDB\Driver\ServerDescription::TYPE_MONGOS = "Mongos";
const string MongoDB\Driver\ServerDescription::TYPE_POSSIBLE_PRIMARY = "PossiblePrimary";
const string MongoDB\Driver\ServerDescription::TYPE_RS_PRIMARY = "RSPrimary";
const string MongoDB\Driver\ServerDescription::TYPE_RS_SECONDARY = "RSSecondary";
const string MongoDB\Driver\ServerDescription::TYPE_RS_ARBITER = "RSArbiter";
const string MongoDB\Driver\ServerDescription::TYPE_RS_OTHER = "RSOther";
const string MongoDB\Driver\ServerDescription::TYPE_RS_GHOST = "RSGhost";
const string MongoDB\Driver\ServerDescription::TYPE_LOAD_BALANCER = "LoadBalancer";
/* メソッド */
final public array getHelloResponse()
final public string getHost()
final public int getLastUpdateTime()
final public int getPort()
final public intnull getRoundTripTime()
final public string getType()
}

定義済み定数

MongoDB\Driver\ServerDescription::TYPE_UNKNOWN

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

MongoDB\Driver\ServerDescription::TYPE_STANDALONE

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

MongoDB\Driver\ServerDescription::TYPE_MONGOS

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

MongoDB\Driver\ServerDescription::TYPE_POSSIBLE_PRIMARY

Replica set possible primary server type, returned by MongoDB\Driver\ServerDescription::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\ServerDescription::TYPE_RS_PRIMARY

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

MongoDB\Driver\ServerDescription::TYPE_RS_SECONDARY

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

MongoDB\Driver\ServerDescription::TYPE_RS_ARBITER

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

MongoDB\Driver\ServerDescription::TYPE_RS_OTHER

Replica set other server type, returned by MongoDB\Driver\ServerDescription::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\ServerDescription::TYPE_RS_GHOST

Replica set ghost server type, returned by MongoDB\Driver\ServerDescription::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.

MongoDB\Driver\ServerDescription::TYPE_LOAD_BALANCER

Load balancer server type, returned by MongoDB\Driver\ServerDescription::getType.

The MongoDB\Driver\TopologyDescription class

はじめに

The MongoDB\Driver\TopologyDescription class is a value object that represents a topology to which the driver is connected. Instances of this class are returned by MongoDB\Driver\Monitoring\TopologyChangedEvent methods.

クラス概要

MongoDB\Driver\TopologyDescription
final class MongoDB\Driver\TopologyDescription {
/* 定数 */
const string MongoDB\Driver\TopologyDescription::TYPE_UNKNOWN = "Unknown";
const string MongoDB\Driver\TopologyDescription::TYPE_SINGLE = "Single";
const string MongoDB\Driver\TopologyDescription::TYPE_SHARDED = "Sharded";
const string MongoDB\Driver\TopologyDescription::TYPE_REPLICA_SET_NO_PRIMARY = "ReplicaSetNoPrimary";
const string MongoDB\Driver\TopologyDescription::TYPE_REPLICA_SET_WITH_PRIMARY = "ReplicaSetWithPrimary";
const string MongoDB\Driver\TopologyDescription::TYPE_LOAD_BALANCED = "LoadBalanced";
/* メソッド */
final public array getServers()
final public string getType()
final public bool hasReadableServer(MongoDB\Driver\ReadPreferencenull $readPreference = null)
final public bool hasWritableServer()
}

定義済み定数

MongoDB\Driver\TopologyDescription::TYPE_UNKNOWN

Unknown topology type, returned by MongoDB\Driver\TopologyDescription::getType.

MongoDB\Driver\TopologyDescription::TYPE_SINGLE

Single server (i.e. direct connection), returned by MongoDB\Driver\TopologyDescription::getType.

MongoDB\Driver\TopologyDescription::TYPE_SHARDED

Sharded cluster, returned by MongoDB\Driver\TopologyDescription::getType.

MongoDB\Driver\TopologyDescription::TYPE_REPLICA_SET_NO_PRIMARY

Replica set with no primary server, returned by MongoDB\Driver\TopologyDescription::getType.

MongoDB\Driver\TopologyDescription::TYPE_REPLICA_SET_WITH_PRIMARY

Replica set with a primary server, returned by MongoDB\Driver\TopologyDescription::getType.

MongoDB\Driver\TopologyDescription::TYPE_LOAD_BALANCED

Load balanced topology, returned by MongoDB\Driver\TopologyDescription::getType.

The MongoDB\Driver\WriteConcernError class

はじめに

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

クラス概要

MongoDB\Driver\WriteConcernError
final class MongoDB\Driver\WriteConcernError {
/* メソッド */
final public int getCode()
final public objectnull getInfo()
final public string getMessage()
}

The MongoDB\Driver\WriteError class

はじめに

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

クラス概要

MongoDB\Driver\WriteError
final class MongoDB\Driver\WriteError {
/* メソッド */
final public int getCode()
final public int getIndex()
final public objectnull getInfo()
final public string getMessage()
}

The MongoDB\Driver\WriteResult class

はじめに

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

クラス概要

MongoDB\Driver\WriteResult
final class MongoDB\Driver\WriteResult {
/* メソッド */
final public intnull getDeletedCount()
final public intnull getInsertedCount()
final public intnull getMatchedCount()
final public intnull getModifiedCount()
final public MongoDB\Driver\Server getServer()
final public intnull getUpsertedCount()
final public array getUpsertedIds()
final public MongoDB\Driver\WriteConcernErrornull getWriteConcernError()
final public array getWriteErrors()
final public bool isAcknowledged()
}