読み込み設定(read preference)の設定
Overview
このガイドでは、 MongoDBで検索操作を実行するときに読み込み設定 (read preference)を設定する方法を学習できます。
始める前に
このガイドのコード例を実行するには、 クイック スタートチュートリアルを完了します。 このチュートリアルでは、サンプル データを使用して MongoDB Atlas インスタンスを設定し、Lambda ウェブ アプリケーションで次のファイルを作成する手順を説明します。
Movie.php
ファイル(movies
コレクション内のドキュメントを表すMovie
モデルを含む)MovieController.php
ファイル(データベース操作を実行するためのshow()
関数を含む)browse_movies.blade.php
データベース操作の結果を表示するための HTML コードを含む ファイル
次のセクションでは、Laravel アプリケーション内のファイルを編集して検索操作コード例を実行し、期待される出力を表示する方法について説明します。
読み込み設定(read preference)の設定
読み取り操作を受信するレプリカセットメンバーを指定するには、 readPreference()
メソッドを使用して読み込み設定 (read preference)を設定します。
readPreference()
メソッドは次のパラメーターを受け入れます:
mode
:(必須)読み込み設定 (read preference)モードを指定する string 値。tagSets
:(任意)特定のレプリカセットノードに対応するキーと値のタグを指定する配列値。options
:(任意)追加の読み込み設定 (read preference)オプションを指定する配列値。
Tip
使用可能な読み込み設定(読み込み設定 (read preference)モードとオプションの完全なリストを表示するには、 MongoDB PHP拡張ドキュメントの MongoDB $Driver\ReadPreference::__construct を参照してください。
次の例では、title
フィールドの値が "Carrie"
であるドキュメントをクエリし、読み込み設定 (read preference)を ReadPreference::SECONDARY_PREFERRED
に設定します。その結果、クエリは、セカンダリレプリカセットメンバーから結果を検索するか、セカンダリが使用できない場合はプライマリ メンバーから結果を検索します。
クエリを指定するには、次の構文を使用します。
$movies = Movie::where('title', 'Carrie') ->readPreference(ReadPreference::SECONDARY_PREFERRED) ->get();
browse_movies
ビューでクエリ結果を表示するには、 MovieController.php
ファイルのshow()
関数を次のコードのように編集します。
class MovieController { public function show() { $movies = Movie::where('title', 'Carrie') ->readPreference(ReadPreference::SECONDARY_PREFERRED) ->get(); return view('browse_movies', [ 'movies' => $movies ]); } }
Title: Carrie Year: 1952 Runtime: 118 IMDB Rating: 7.5 IMDB Votes: 1458 Plot: Carrie boards the train to Chicago with big ambitions. She gets a job stitching shoes and her sister's husband takes almost all of her pay for room and board. Then she injures a finger and ... Title: Carrie Year: 1976 Runtime: 98 IMDB Rating: 7.4 IMDB Votes: 115528 Plot: A shy, outcast 17-year old girl is humiliated by her classmates for the last time. Title: Carrie Year: 2002 Runtime: 132 IMDB Rating: 5.5 IMDB Votes: 7412 Plot: Carrie White is a lonely and painfully shy teenage girl with telekinetic powers who is slowly pushed to the edge of insanity by frequent bullying from both her classmates and her domineering, religious mother. Title: Carrie Year: 2013 Runtime: 100 IMDB Rating: 6 IMDB Votes: 98171 Plot: A reimagining of the classic horror tale about Carrie White, a shy girl outcast by her peers and sheltered by her deeply religious mother, who unleashes telekinetic terror on her small town after being pushed too far at her senior prom.