Overview
In this guide, you can learn how to configure write concern, read concern, and read preference options to modify the way that the MongoDB PHP Library runs create, read, update, and delete (CRUD) operations on replica sets.
You can set write concern, read concern, and read preference options at the following levels:
Client, which sets the default for all operation executions unless overridden
Session
Transaction
Database
Collection
This list also indicates the increasing order of precedence of the option settings. For example, if you set a read concern level for a transaction, it will override a read concern level inherited from the client.
These options allow you to customize the causal consistency and availability of the data in your replica sets. To see a full list of read preference, read concern, and write concern options, see the following guides in the MongoDB Server manual:
Configure Read and Write Operations
You can control how the library routes read operations by setting a read preference. You can also control how the library waits for acknowledgment of read and write operations on a replica set by setting read and write concerns.
This section shows how to configure the read preference, read concern, and write concern at various levels by passing an options array parameter to any one of the following methods:
MongoDB\Client::__construct(): Configures client-level settings
MongoDB\Client::startSession(): Configures session-level settings
MongoDB\Driver\Session::startTransaction(): Configures transaction-level settings
MongoDB\Client::getDatabase(): Configures database-level settings
MongoDB\Client::getCollection(): Configures collection-level settings
Client Configuration
This example shows how to set the read preference, read concern, and
write concern of a MongoDB\Client instance by passing an array to
the constructor. The code configures the following settings:
secondaryread preference: Read operations retrieve data from secondary replica set memberslocalread concern: Read operations return the instance's most recent data without guaranteeing that the data has been written to a majority of the replica set members2write concern: The primary and one secondary replica set member must acknowledge the write operation
$clientOptions = [ 'readPreference' => 'secondary', 'readConcernLevel' => 'local', 'w' => '2', ]; $client = new Client('mongodb://localhost:27017', $clientOptions);
Alternatively, you can specify the read and write settings in the connection
URI, which is passed as a parameter to the MongoDB\Client constructor:
$uri = 'mongodb://localhost:27017/?readPreference=secondary&readConcernLevel=local&w=2'; $client = new Client($uri);
Note
The readPreference, readConcernLevel, and w client options accept
string values. When configuring read and write settings at any other level,
you must assign values of type MongoDB\Driver\ReadPreference,
MongoDB\Driver\ReadConcern, and MongoDB\Driver\WriteConcern to the corresponding
options.
Session Configuration
This example shows how to set the read preference, read concern, and
write concern of a session by passing an array to the startSession()
method. The code configures the following settings:
PRIMARY_PREFERREDread preference: Read operations retrieve data from the primary replica set member, or secondary members if the primary is unavailableLOCALread concern: Read operations return the instance's most recent data without guaranteeing that the data has been written to a majority of the replica set membersMAJORITYwrite concern: The majority of all replica set members must acknowledge the write operation
$sessionOptions = [ 'readPreference' => new ReadPreference(ReadPreference::PRIMARY_PREFERRED), 'readConcern' => new ReadConcern(ReadConcern::LOCAL), 'writeConcern' => new WriteConcern(WriteConcern::MAJORITY), ]; $session = $client->startSession($sessionOptions);
Transaction Configuration
This example shows how to set the read preference, read concern, and
write concern of a transaction by passing an array to the startTransaction()
method. The code configures the following settings:
PRIMARYread preference: Read operations retrieve data from the primary replica set memberMAJORITYread concern: Read operations return the instance's most recent data that has been written to a majority of replica set members1write concern: The primary replica set member must acknowledge the write operation
$transactionOptions = [ 'readPreference' => new ReadPreference(ReadPreference::PRIMARY), 'readConcern' => new ReadConcern(ReadConcern::MAJORITY), 'writeConcern' => new WriteConcern(1), ]; $session->startTransaction($transactionOptions);
Database Configuration
This example shows how to set the read preference, read concern, and
write concern of a database called test_database by passing an options
array to the getDatabase() method. The code configures the following settings:
PRIMARY_PREFERREDread preference: Read operations retrieve data from the primary replica set member, or secondary members if the primary is unavailableAVAILABLEread concern: Read operations return the instance's most recent data without guaranteeing that the data has been written to a majority of the replica set membersMAJORITYwrite concern: The majority of all replica set members must acknowledge the write operation
$db = $client->getDatabase('test_database', [ 'readPreference' => new ReadPreference(ReadPreference::PRIMARY_PREFERRED), 'readConcern' => new ReadConcern(ReadConcern::AVAILABLE), 'writeConcern' => new WriteConcern(WriteConcern::MAJORITY), ]);
Collection Configuration
This example shows how to set the read preference, read concern, and
write concern of a collection called test_collection by passing an options
array to the getCollection() method. The code configures the following settings:
SECONDARY_PREFERREDread preference: Read operations retrieve data from secondary replica set members, or the primary members if no secondaries are availableAVAILABLEread concern: Read operations return the instance's most recent data without guaranteeing that the data has been written to a majority of the replica set members0write concern: Requests no acknowledgment of the write operation
$collection = $client->getCollection('test_database', 'test_collection', [ 'readPreference' => new ReadPreference(ReadPreference::SECONDARY_PREFERRED), 'readConcern' => new ReadConcern(ReadConcern::AVAILABLE), 'writeConcern' => new WriteConcern(0), ]);
Advanced Read Configurations
This section shows how to further customize your read operation settings in the following ways:
Tag Sets
The MongoDB Server allows you to apply key-value tags to replica-set members according to any criteria you choose. You can then use those tags to target one or more members for a read operation.
By default, the MongoDB PHP Library ignores tags when choosing a member
to read from. To instruct the MongoDB PHP Library to prefer certain tags,
pass them as a parameter to your MongoDB\Driver\ReadPreference class
constructor. Then, set the MongoDB\Driver\ReadPreference object as
the value of the readPreference database option.
Suppose you are connected to a replica set that contains members hosted
at multiple data centers across the United States. This code example sets
the readPreference option to a tag set that instructs test_database
to prefer reads from secondary replica set members in the following order:
Members from the New York data center (
['dc' => 'ny'])Members from the San Francisco data center (
['dc' => 'sf'])Any secondary members (
[])
$readPreference = new ReadPreference( ReadPreference::RP_SECONDARY, [ ['dc' => 'ny'], ['dc' => 'sf'], [], ], ); $db = $client->getDatabase( 'test_database', ['readPreference' => $readPreference], );
Load Balancing
When connecting to a sharded cluster or a replica set, the PHP library uses load balancing to handle read and write requests. Load balancing allows the library to distribute these requests across multiple servers to avoid overwhelming any one server and ensure optimal performance.
When connecting to a sharded cluster, the PHP library determines the closest mongos
instance by calculating which one has the lowest network round-trip time. Then, the library
determines the latency window by adding this mongos's average round-trip time to the
localThresholdMS value. The library load balances requests
across up to two random mongos instances that fall within the latency window. For each request,
the library chooses the server with the lower operation load by determining its operationCount
value.
When connecting to a replica set, the PHP library first selects replica set members
according to your read preference. Then, the library follows the same process as
described in the preceding paragraph. After calculating the latency window, the library
selects up to two random replica set members that fall within the window and chooses
the member with the lower operationCount value to receive the request.
Tip
To learn more about load balancing, see Sharded Cluster Balancer in the MongoDB Server manual.
To learn how to customize the library's server selection behavior, see Server Selection and Discovery Options in the Specify Connection Options guide.
Local Threshold
The PHP library uses the local threshold value to calculate the latency window for server selection. This value determines the servers that are eligible to receive read and write requests.
By default, the library uses only mongos instances or replica set members whose
ping times are within 15 milliseconds of the nearest server. To
distribute reads among servers with higher latencies, pass an options array to
the MongoDB\Client constructor that sets the localThresholdMS option.
The following example specifies a local threshold of 35 milliseconds:
$options = [ 'replicaSet' => 'repl0', 'readPreference' => new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED), 'localThresholdMS' => 35, ]; $client = new Client('mongodb://localhost:27017', [], $options);
In the preceding example, the MongoDB PHP Library distributes reads among matching members within 35 milliseconds of the closest member's ping time.
Note
The MongoDB PHP Library ignores the value of localThresholdMS when communicating with a
replica set through a mongos instance. In this case, use the
localThreshold
command-line option.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following library API documentation:
To learn more about the startTransaction() method, see MongoDB\Driver\Session::startTransaction() in the extension API documentation.