Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
PHP ライブラリ マニュアル
/ /

Retrieve Data

このガイドでは、 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 つのドキュメントを検索するには、 MongoDB\Collection::findOne()メソッドを呼び出し、検索するドキュメントの基準を指定するクエリフィルターを渡します。

findOne()メソッドは、 arrayobject 、または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",
... }

Tip

並び替え順

ソート条件が指定されていない場合、 findOne()メソッドはディスク上の自然な順序で最初のドキュメントを返します。

コレクション内の複数のドキュメントを検索するには、検索するドキュメントの基準を指定するクエリフィルターを 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()メソッドの動作を変更できます。 次の表では、 配列に設定できるオプションの一部を説明しています。

オプション
説明

batchSize

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

collation

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

comment

The comment to attach to the operation.
Type: any BSON type

cursorType

The type of cursor to use for the operation. The default value is MongoDB\Operation\Find::NON_TAILABLE.
Type: MongoDB\Operation\Find

limit

The maximum number of documents the operation can return.
Type: integer

skip

The number of documents to skip before returning results.
Type: integer

sort

The order in which the operation returns matching documents.
Type: array|object

typeMap

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 オプションを割り当てます。

次の表では、照合を構成するために設定できるフィールドについて説明しています。

フィールド
説明

locale

(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

caseLevel

(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 base
characters and case.

- If strength is 2, the PHP library compares base
characters, 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

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Data Type: string
Default: "off"

strength


Data Type: int
Default: 3

numericOrdering

(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

alternate

(Optional) Specifies whether the library considers whitespace and punctuation as base characters for comparison purposes.

Data Type: string
Default: "non-ignorable"

maxVariable

(Optional) Specifies which characters the library considers ignorable when the alternate field is set to "shifted".

Data Type: string
Default: "punct"

backwards

(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.

Data Type: bool
Default: false

照合と各フィールドに可能な値の詳細については、 MongoDB Serverマニュアルの「 照合 」エントリを参照してください。

クエリフィルターの詳細については、「クエリの指定」ガイドを参照してください。

このガイドで説明されているメソッドの詳細については、次の API ドキュメントを参照してください。

戻る

クエリ ドキュメント

項目一覧