Skip to content

Commit 08d54d8

Browse files
norareidyGromNaN
andauthored
DOCSP-46438: Read preference (#3260)
* DOCSP-46438: Read preference * edits * tip * fix test * fix * code * JS feedback * Switch example to SECONDARY_PREFERRED * JT feedback * apply phpcbf formatting * tests --------- Co-authored-by: Jérôme Tamarelle <jerome.tamarelle@mongodb.com>
1 parent 4c45ea8 commit 08d54d8

File tree

4 files changed

+171
-4
lines changed

4 files changed

+171
-4
lines changed

docs/fundamentals/read-operations.txt

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,8 @@ method:
359359
results in a specified order based on field values
360360
- :ref:`laravel-retrieve-one` uses the ``first()`` method to return the first document
361361
that matches the query filter
362+
- :ref:`laravel-read-pref` uses the ``readPreference()`` method to direct the query
363+
to specific replica set members
362364

363365
.. _laravel-skip-limit:
364366

@@ -606,3 +608,110 @@ field.
606608

607609
To learn more about the ``orderBy()`` method, see the
608610
:ref:`laravel-sort` section of this guide.
611+
612+
.. _laravel-read-pref:
613+
614+
Set a Read Preference
615+
~~~~~~~~~~~~~~~~~~~~~
616+
617+
To specify which replica set members receive your read operations,
618+
set a read preference by using the ``readPreference()`` method.
619+
620+
The ``readPreference()`` method accepts the following parameters:
621+
622+
- ``mode``: *(Required)* A string value specifying the read preference
623+
mode.
624+
625+
- ``tagSets``: *(Optional)* An array value specifying key-value tags that correspond to
626+
certain replica set members.
627+
628+
- ``options``: *(Optional)* An array value specifying additional read preference options.
629+
630+
.. tip::
631+
632+
To view a full list of available read preference modes and options, see
633+
:php:`MongoDB\Driver\ReadPreference::__construct </manual/en/mongodb-driver-readpreference.construct.php>`
634+
in the MongoDB PHP extension documentation.
635+
636+
The following example queries for documents in which the value of the ``title``
637+
field is ``"Carrie"`` and sets the read preference to ``ReadPreference::SECONDARY_PREFERRED``.
638+
As a result, the query retrieves the results from secondary replica set
639+
members or the primary member if no secondaries are available:
640+
641+
.. tabs::
642+
643+
.. tab:: Query Syntax
644+
:tabid: query-syntax
645+
646+
Use the following syntax to specify the query:
647+
648+
.. literalinclude:: /includes/fundamentals/read-operations/ReadOperationsTest.php
649+
:language: php
650+
:dedent:
651+
:start-after: start-read-pref
652+
:end-before: end-read-pref
653+
654+
.. tab:: Controller Method
655+
:tabid: controller
656+
657+
To see the query results in the ``browse_movies`` view, edit the ``show()`` function
658+
in the ``MovieController.php`` file to resemble the following code:
659+
660+
.. io-code-block::
661+
:copyable: true
662+
663+
.. input::
664+
:language: php
665+
666+
class MovieController
667+
{
668+
public function show()
669+
{
670+
$movies = Movie::where('title', 'Carrie')
671+
->readPreference(ReadPreference::SECONDARY_PREFERRED)
672+
->get();
673+
674+
return view('browse_movies', [
675+
'movies' => $movies
676+
]);
677+
}
678+
}
679+
680+
.. output::
681+
:language: none
682+
:visible: false
683+
684+
Title: Carrie
685+
Year: 1952
686+
Runtime: 118
687+
IMDB Rating: 7.5
688+
IMDB Votes: 1458
689+
Plot: Carrie boards the train to Chicago with big ambitions. She gets a
690+
job stitching shoes and her sister's husband takes almost all of her pay
691+
for room and board. Then she injures a finger and ...
692+
693+
Title: Carrie
694+
Year: 1976
695+
Runtime: 98
696+
IMDB Rating: 7.4
697+
IMDB Votes: 115528
698+
Plot: A shy, outcast 17-year old girl is humiliated by her classmates for the
699+
last time.
700+
701+
Title: Carrie
702+
Year: 2002
703+
Runtime: 132
704+
IMDB Rating: 5.5
705+
IMDB Votes: 7412
706+
Plot: Carrie White is a lonely and painfully shy teenage girl with telekinetic
707+
powers who is slowly pushed to the edge of insanity by frequent bullying from
708+
both her classmates and her domineering, religious mother.
709+
710+
Title: Carrie
711+
Year: 2013
712+
Runtime: 100
713+
IMDB Rating: 6
714+
IMDB Votes: 98171
715+
Plot: A reimagining of the classic horror tale about Carrie White, a shy girl
716+
outcast by her peers and sheltered by her deeply religious mother, who unleashes
717+
telekinetic terror on her small town after being pushed too far at her senior prom.

docs/includes/fundamentals/read-operations/ReadOperationsTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use App\Models\Movie;
88
use Illuminate\Support\Facades\DB;
9+
use MongoDB\Driver\ReadPreference;
910
use MongoDB\Laravel\Tests\TestCase;
1011

1112
class ReadOperationsTest extends TestCase
@@ -33,6 +34,8 @@ protected function setUp(): void
3334
['title' => 'movie_a', 'plot' => 'this is a love story'],
3435
['title' => 'movie_b', 'plot' => 'love is a long story'],
3536
['title' => 'movie_c', 'plot' => 'went on a trip'],
37+
['title' => 'Carrie', 'year' => 1976],
38+
['title' => 'Carrie', 'year' => 2002],
3639
]);
3740
}
3841

@@ -164,4 +167,20 @@ public function arrayElemMatch(): void
164167
$this->assertNotNull($movies);
165168
$this->assertCount(2, $movies);
166169
}
170+
171+
/**
172+
* @runInSeparateProcess
173+
* @preserveGlobalState disabled
174+
*/
175+
public function testReadPreference(): void
176+
{
177+
// start-read-pref
178+
$movies = Movie::where('title', 'Carrie')
179+
->readPreference(ReadPreference::SECONDARY_PREFERRED)
180+
->get();
181+
// end-read-pref
182+
183+
$this->assertNotNull($movies);
184+
$this->assertCount(2, $movies);
185+
}
167186
}

docs/includes/query-builder/QueryBuilderTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use MongoDB\BSON\ObjectId;
1212
use MongoDB\BSON\Regex;
1313
use MongoDB\Collection;
14+
use MongoDB\Driver\ReadPreference;
1415
use MongoDB\Laravel\Tests\TestCase;
1516

1617
use function file_get_contents;
@@ -452,6 +453,18 @@ public function testCursorTimeout(): void
452453
$this->assertInstanceOf(\Illuminate\Support\Collection::class, $result);
453454
}
454455

456+
public function testReadPreference(): void
457+
{
458+
// begin query read pref
459+
$result = DB::table('movies')
460+
->where('runtime', '>', 240)
461+
->readPreference(ReadPreference::SECONDARY_PREFERRED)
462+
->get();
463+
// end query read pref
464+
465+
$this->assertInstanceOf(\Illuminate\Support\Collection::class, $result);
466+
}
467+
455468
public function testNear(): void
456469
{
457470
$this->importTheaters();

docs/query-builder.txt

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -840,6 +840,7 @@ to use the following MongoDB-specific query operations:
840840
- :ref:`Run MongoDB Query API operations <laravel-query-builder-whereRaw>`
841841
- :ref:`Match documents that contain array elements <laravel-query-builder-elemMatch>`
842842
- :ref:`Specify a cursor timeout <laravel-query-builder-cursor-timeout>`
843+
- :ref:`Specify a read preference <laravel-query-builder-read-pref>`
843844
- :ref:`Match locations by using geospatial searches <laravel-query-builder-geospatial>`
844845

845846
.. _laravel-query-builder-exists:
@@ -1033,6 +1034,31 @@ to specify a maximum duration to wait for cursor operations to complete.
10331034
`MongoDB\Collection::find() <https://www.mongodb.com/docs/php-library/current/reference/method/MongoDBCollection-find/>`__
10341035
in the PHP Library documentation.
10351036

1037+
.. _laravel-query-builder-read-pref:
1038+
1039+
Specify a Read Preference Example
1040+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1041+
1042+
You can control how the {+odm-short+} directs read operations to replica
1043+
set members by setting a read preference.
1044+
1045+
The following example queries the ``movies`` collection for documents
1046+
in which the ``runtime`` value is greater than ``240``. The example passes a
1047+
value of ``ReadPreference::SECONDARY_PREFERRED`` to the ``readPreference()``
1048+
method, which sends the query to secondary replica set members
1049+
or the primary member if no secondaries are available:
1050+
1051+
.. literalinclude:: /includes/query-builder/QueryBuilderTest.php
1052+
:language: php
1053+
:dedent:
1054+
:start-after: begin query read pref
1055+
:end-before: end query read pref
1056+
1057+
.. tip::
1058+
1059+
To learn more about read preferences, see :manual:`Read Preference
1060+
</core/read-preference/>` in the MongoDB {+server-docs-name+}.
1061+
10361062
.. _laravel-query-builder-geospatial:
10371063

10381064
Match Locations by Using Geospatial Operations
@@ -1061,7 +1087,7 @@ in the {+server-docs-name+}.
10611087
.. _laravel-query-builder-geospatial-near:
10621088

10631089
Near a Position Example
1064-
~~~~~~~~~~~~~~~~~~~~~~~
1090+
^^^^^^^^^^^^^^^^^^^^^^^
10651091

10661092
The following example shows how to use the ``near`` query operator
10671093
with the ``where()`` query builder method to match documents that
@@ -1081,7 +1107,7 @@ in the {+server-docs-name+}.
10811107
.. _laravel-query-builder-geospatial-geoWithin:
10821108

10831109
Within an Area Example
1084-
~~~~~~~~~~~~~~~~~~~~~~
1110+
^^^^^^^^^^^^^^^^^^^^^^
10851111

10861112
The following example shows how to use the ``geoWithin``
10871113
query operator with the ``where()``
@@ -1098,7 +1124,7 @@ GeoJSON object:
10981124
.. _laravel-query-builder-geospatial-geoIntersects:
10991125

11001126
Intersecting a Geometry Example
1101-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1127+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
11021128

11031129
The following example shows how to use the ``geoInstersects``
11041130
query operator with the ``where()`` query builder method to
@@ -1114,7 +1140,7 @@ the specified ``LineString`` GeoJSON object:
11141140
.. _laravel-query-builder-geospatial-geoNear:
11151141

11161142
Proximity Data for Nearby Matches Example
1117-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1143+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
11181144

11191145
The following example shows how to use the ``geoNear`` aggregation operator
11201146
with the ``raw()`` query builder method to perform an aggregation that returns

0 commit comments

Comments
 (0)