Docs Menu

単一フィールド インデックス

Single field indexes are indexes with a reference to a single field of a document in a collection. These indexes improve single field query and sort performance. They also support TTL Indexes that automatically remove documents from a collection after a certain amount of time or at a specified clock time.

When creating a single-field index, you must specify the following details:

  • The field on which to create the index

  • The sort order for the indexed values as either ascending or descending

注意

The default _id_ index is an example of a single-field index. This index is automatically created on the _id field when a new collection is created.

このガイドの例では、 Atlas サンプル データセットsample_mflixデータベースのmoviesコレクションを使用します。 MongoDB Atlas クラスターを無料で作成して、サンプル データセットをロードする方法については、 「 Atlas を使い始める 」ガイドを参照してください。

Use the MongoDB\Collection::createIndex() method to create a single field index. The following example creates an index in ascending order on the title field:

$indexName = $collection->createIndex(['title' => 1]);

以下は、前のコード例で作成されたインデックスによってカバーされるクエリの例です。

$document = $collection->findOne(['title' => 'Sweethearts']);
echo json_encode($document), PHP_EOL;
{"_id":...,"plot":"A musical comedy duo...",
"genres":["Musical"],...,"title":"Sweethearts",...}

インデックスを管理する方法を示す実行可能な例については、「 インデックスを使用してクエリを最適化する 」を参照してください。

To learn more about single field indexes, see Single Field Indexes in the MongoDB Server manual.

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