php[world] 2019 — 25 years of PHP

MongoCommandCursor::setReadPreference

(PECL mongo >=1.6.0)

MongoCommandCursor::setReadPreferenceSet the read preference for this command

Description

public MongoCommandCursor::setReadPreference ( string $read_preference [, array $tags ] ) : MongoCommandCursor

Parameters

read_preference

The read preference mode: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, or MongoClient::RP_NEAREST.

tags

An array of zero or more tag sets, where each tag set is itself an array of criteria used to match tags on replica set members.

Return Values

Returns this cursor.

Errors/Exceptions

Emits E_WARNING if either parameter is invalid, or if one or more tag sets are provided with the MongoClient::RP_PRIMARY read preference mode.

Examples

Example #1 MongoCommandCursor::setReadPreference() tag set array syntax example

<?php

$m 
= new MongoClient('mongodb://rs1.example.com:27017', array('replicaSet' => 'myReplSetName'));
$collection $m->selectCollection('test''people');

$cursor $collection->aggregateCursor( [
    [ 
'$group' => [ '_id' => '$name''points' => [ '$sum' => '$points' ] ] ],
    [ 
'$sort' => [ 'points' => -] ],
] );

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$cursor->setReadPreference(MongoClient::RP_NEAREST, [
    [ 
'dc' => 'east''use' => 'reporting' ],
    [ 
'dc' => 'west' ],
] );

foreach (
$cursor as $person) {
    
// ...
}

// If the read preference is changed, it will be used the next time the cursor
// is rewound and the command is re-executed.
$cursor->setReadPreference(MongoClient::RP_PRIMARY);

foreach (
$cursor as $person) {
    
// ...
}

?>

See Also

add a note add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top