Compound Indexes
Overview
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 createsingle field indexes.Sample Data
The examples in this guide use the movies
collection in the sample_mflix
database from the
Create a Compound Index
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;
{"_id":...,"title":"Before Sunrise",...,"year":1995,...}
Additional Information
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.
API Documentation
To learn more about any of the methods discussed in this guide, see the following API documentation: