read-pref

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset

Available tabs: other tabs: query-syntax, controller -->

Set a Read Preference

Overview

In this guide, you can learn how to set a read preference when performing find operations with Laravel MongoDB.

Before You Get Started

To run the code examples in this guide, complete the [Quick Start](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started.md#std-label-laravel-quick-start tutorial. This tutorial provides instructions on setting up a MongoDB Atlas instance with sample data and creating the following files in your Laravel web application:

  • Movie.php file, which contains a Movie model to represent documents in the movies collection

  • MovieController.php file, which contains a show() function to run database operations

  • browse_movies.blade.php file, which contains HTML code to display the results of database operations

The following sections describe how to edit the files in your Laravel application to run the find operation code examples and view the expected output.

Set a Read Preference

To specify which replica set members receive your read operations, set a read preference by using the readPreference() method.

The readPreference() method accepts the following parameters:

  • mode: (Required) A string value specifying the read preference mode.

  • tagSets: (Optional) An array value specifying key-value tags that correspond to certain replica set members.

  • options: (Optional) An array value specifying additional read preference options.

Tip:

To view a full list of available read preference modes and options, see MongoDB\Driver\ReadPreference::__construct in the MongoDB PHP extension documentation.

The following example queries for documents in which the value of the title field is “Carrie” and sets the read preference to ReadPreference::SECONDARY_PREFERRED. As a result, the query retrieves the results from secondary replica set members or the primary member if no secondaries are available:

Query Syntax

Use the following syntax to specify the query:

$movies = Movie::where('title', 'Carrie')
    ->readPreference(ReadPreference::SECONDARY_PREFERRED)
    ->get();

Additional Information

To learn how to retrieve data based on filter criteria, see the [Retrieve MongoDB Data](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query/retrieve.md#std-label-laravel-fundamentals-read-retrieve guide.

To learn how to modify the way that the Laravel Integration returns results, see the [Modify Query Results](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query/modify-results.md#std-label-laravel-read-modify-results guide.