Docs Menu
Docs Home
/ / /
PHP Library Manual
/

Compound Indexes

On this page

  • Overview
  • Sample Data
  • Create a Compound Index
  • Additional Information
  • API Documentation

Compound indexes hold references to multiple fields within a collection's documents, improving query and sort performance. You can create a compound index on a collection by using the MongoDB\Collection::createIndex() method and the same syntax that you use to create single field indexes.

The examples in this guide use the movies collection in the sample_mflix database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.

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

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

The following is an example of a query that is covered by the index created in the preceding code example:

$document = $collection->findOne(
['title' => ['$regex' => 'Sunrise'],
'year' => ['$gte' => 1990]]
);
echo json_encode($document), PHP_EOL;

To learn more about compound indexes, see Compound Indexes in the MongoDB Server manual.

To view runnable examples that demonstrate how to manage indexes, see Optimize Queries by Using Indexes.

To learn more about any of the methods discussed in this guide, see the following API documentation:

Back

Single Field Indexes