Overview
このガイドでは、 MongoDB PHPライブラリを使用して、読み取り操作によりMongoDBコレクションからデータを検索する方法を学習できます。 コレクションで MongoDB\Collection::find()
またはMongoDB\Collection::findOne()
メソッドを呼び出して、基準のセットに一致するドキュメントを検索できます。
サンプル データ
このガイドの例では、 Atlasサンプルデータセットのsample_training
データベースのcompanies
コレクションを使用します。 PHPアプリケーションからこのコレクションにアクセスするには、Atlas クラスターに接続するMongoDB\Client
をインスタンス化し、 $collection
変数に次の値を割り当てます。
$collection = $client->sample_training->companies;
MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「Atlas を使い始める」ガイドを参照してください。
ドキュメントの検索
MongoDB PHPライブラリには、コレクションからドキュメントを取得するための 2 つの方法MongoDB\Collection::findOne()
とMongoDB\Collection::find()
が含まれています。 これらのメソッドはクエリフィルターを受け取り、1 つ以上の一致するドキュメントを返します。 クエリフィルターは、ドライバーがクエリ内のドキュメントを検索するために使用する検索条件を指定します。
Tip
クエリフィルターの詳細については、「 クエリの指定」ガイドを参照してください。
1 つのドキュメントの検索
コレクション内の 1 つのドキュメントを検索するには、 MongoDB\Collection::findOne()
メソッドを呼び出し、検索するドキュメントの基準を指定するクエリフィルターを渡します。
findOne()
メソッドは、 array
、 object
、またはnull
の値を返します。 クエリフィルターがドキュメントと一致する場合、メソッドはドキュメントを含むarray|object
インスタンスを返します。 戻り値の型は、 typeMap
オプションの値によって異なります。 クエリフィルターがどのドキュメントにも一致しない場合、メソッドはnull
を返します。
Tip
typeMap
などのfindOne()
オプションの詳細については、このガイドの「検索動作の変更」セクションを参照してください。
クエリフィルターが複数のドキュメントに一致する場合、 findOne()
メソッドは検索した結果から最初に一致するドキュメントを返します。
次の例では、 findOne()
メソッドを使用して、 name
フィールドの値が'LinkedIn'
になっている最初のドキュメントを検索します。
$document = $collection->findOne(['name' => 'LinkedIn']); echo json_encode($document), PHP_EOL;
{"_id":{"$oid":"..."},"name":"LinkedIn","permalink":"linkedin","crunchbase_url": "http:\/\/www.crunchbase.com\/company\/linkedin","homepage_url":"http:\/\/linkedin.com", ... }
複数ドキュメントの検索
コレクション内の複数のドキュメントを検索するには、検索するドキュメントの基準を指定するクエリフィルターを MongoDB\Collection::find()
メソッドに渡します。
次の例では、 find()
メソッドを使用して、 founded_year
フィールドの値が1970
であるすべてのドキュメントを検索します。
$results = $collection->find(['founded_year' => 1970]);
find()
メソッドはMongoDB\Driver\Cursor
のインスタンスを返します。これを反復処理して一致するドキュメントを確認できます。 カーソルは、アプリケーションがデータベースの結果を反復処理しながら、特定の時点でメモリ内に結果のサブセットのみを保持できるようにするメカニズムです。 カーソルは、 find()
メソッドが大量のドキュメントを返す場合に便利です。
次の例に示すように、 foreach
ループを使用して、カーソル内のドキュメントを反復処理できます。
foreach ($results as $doc) { echo json_encode($doc), PHP_EOL; }
{"_id":{"$oid":"..."},"name":"Mitsubishi Motors","permalink":"mitsubishi-motors", "crunchbase_url":"http:\/\/www.crunchbase.com\/company\/mitsubishi-motors", ... } {"_id":{"$oid":"..."},"name":"Western Digital","permalink":"western-digital", "crunchbase_url":"http:\/\/www.crunchbase.com\/company\/western-digital", ... } {"_id":{"$oid":"..."},"name":"Celarayn","permalink":"celarayn","crunchbase_url": "http:\/\/www.crunchbase.com\/company\/celarayn", ... }
注意
すべてのドキュメントの検索
コレクション内のすべてのドキュメントを検索するには、 find()
メソッドに空のフィルターを渡します。
$cursor = $collection->find([]);
検索動作の変更
オプション値を指定する配列をパラメーターとして渡すことで、 MongoDB\Collection::find()
メソッドとMongoDB\Collection::findOne()
メソッドの動作を変更できます。 次の表では、 配列に設定できるオプションの一部を説明しています。
オプション | 説明 |
---|---|
| The maximum number of documents within each batch returned in a query result. By default,
the find command has an initial batch size of 101 documents
and a maximum size of 16 mebibytes (MiB) for each subsequent batch. This
option can enforce a smaller limit than 16 MiB, but not a larger
one. If you set batchSize to a limit that results in batches larger than
16 MiB, this option has no effect.Type: integer |
| The collation to use for the operation. The default value is the collation
specified for the collection. To learn more, see the Collation
section of this page. Type: array|object |
| The comment to attach to the operation. Type: any BSON type |
| The type of cursor to use for the operation. The default value is
MongoDB\Operation\Find::NON_TAILABLE .Type: MongoDB\Operation\Find |
| The maximum number of documents the operation can return. Type: integer |
| The number of documents to skip before returning results. Type: integer |
| The order in which the operation returns matching documents. Type: array|object |
| The type map to apply to cursors, which determines how BSON documents
are converted to PHP values. The default value is the collection's type map. Type: array |
次の例では、 find()
メソッドを使用して、 number_of_employees
フィールドの値が1000
であるすべてのドキュメントを検索します。 この例ではlimit
オプションを使用して最大5
の結果が返されます。
$results = $collection->find( ['number_of_employees' => 1000], ['limit' => 5], ); foreach ($results as $doc) { echo json_encode($doc), PHP_EOL; }
オプションの完全なリストについては、 findOne()およびfind()パラメーターのAPIドキュメントを参照してください。
照合
操作の 照合 を指定するには、collation
オプションを設定する $options
配列パラメータを操作メソッドに渡します。照合ルールを構成する配列に collation
オプションを割り当てます。
次の表では、照合を構成するために設定できるフィールドについて説明しています。
フィールド | 説明 |
---|---|
| (Required) Specifies the International Components for Unicode (ICU) locale. For a
list of supported locales, see Collation Locales and Default Parameters
in the MongoDB Server manual. Data Type: string |
| (Optional) Specifies whether to include case comparison. When set to true , the comparison behavior depends on the value of
the strength field:- If strength is 1 , the PHP library compares basecharacters and case. - If strength is 2 , the PHP library compares basecharacters, diacritics, other secondary differences, and case. - If strength is any other value, this field is ignored.When set to false , the PHP library doesn't include case comparison at
strength level 1 or 2 .Data Type: bool Default: false |
| (Optional) Specifies the sort order of case differences during tertiary
level comparisons. Data Type: string Default: "off" |
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. Data Type: int Default: 3 |
| (Optional) Specifies whether the driver compares numeric strings as numbers. If set to true , the PHP library compares numeric strings as numbers.
For example, when comparing the strings "10" and "2", the library uses the
strings' numeric values and treats "10" as greater than "2".If set to false , the PHP library compares numeric strings
as strings. For example, when comparing the strings "10" and "2", the library
compares one character at a time and treats "10" as less than "2".For more information, see Collation Restrictions
in the MongoDB Server manual. Data Type: bool Default: false |
| (Optional) Specifies whether the library considers whitespace and punctuation as base
characters for comparison purposes. Data Type: string Default: "non-ignorable" |
| (Optional) Specifies which characters the library considers ignorable when
the alternate field is set to "shifted" .Data Type: string Default: "punct" |
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. Data Type: bool Default: false |
照合と各フィールドに可能な値の詳細については、 MongoDB Serverマニュアルの「 照合 」エントリを参照してください。
詳細情報
クエリフィルターの詳細については、「クエリの指定」ガイドを参照してください。
API ドキュメント
このガイドで説明されているメソッドの詳細については、次の API ドキュメントを参照してください。