Multikey Indexes
Overview
Multikey indexes are indexes that improve the performance of queries
on array-valued fields. You can create a multikey index on a collection
by using the MongoDB\Collection::createIndex()
method and the same
syntax that you use to create single field or compound indexes.
Sample Data
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.
Create a Multikey Index
Use the MongoDB\Collection::createIndex()
method to create a
multikey index. The following example creates an index in ascending
order on the array-valued cast
field:
$indexName = $collection->createIndex(['cast' => 1]);
The following is an example of a query that is covered by the index created in the preceding code example:
$document = $collection->findOne( ['cast' => ['$in' => ['Aamir Khan', 'Kajol']]] ); echo json_encode($document), PHP_EOL;
{"_id":...,"title":"Holi",...,"cast":["Ashutosh Gowariker", "Aamir Khan","Rahul Ranade","Sanjeev Gandhi"],...}
Additional Information
Multikey indexes behave differently from other indexes in terms of query coverage, index bound computation, and sort behavior. To learn more about the behavior and limitations of multikey indexes, see Multikey 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: