Optimize Queries by Using Indexes
On this page
Overview
On this page, you can see copyable code examples that show how to manage different types of indexes by using the MongoDB PHP Library.
Tip
To learn more about working with indexes, see the Index Considerations and Management guide. To learn more about any of the indexes shown on this page, see the link provided in each section.
To use an example from this page, copy the code example into the
sample application or your own application.
Make sure to set the MONGODB_URI
environment variable to the
connection string for your MongoDB deployment, and replace the
<database>
and <collection>
placeholders with values for your
target namespace.
Sample Application
You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:
Ensure you have the MongoDB PHP Library installed in your project. To learn more about installing the MongoDB PHP Library, see the Download and Install guide.
Copy the following code and paste it into a new
.php
file.Copy a code example from this page and paste it on the specified lines in the file.
1 2 3 require __DIR__ . '/../vendor/autoload.php'; 4 5 $uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset'); 6 $client = new MongoDB\Client($uri); 7 8 $collection = $client->selectCollection('<database>', '<collection>'); 9 10 // Start example code here 11 12 // End example code here
Some examples use the toJSON()
function to represent change events, which are BSON
documents, as Extended JSON. To use this function, paste the following code into your
application file:
function toJSON(object $document): string { return MongoDB\BSON\Document::fromPHP($document)->toRelaxedExtendedJSON(); }
Single Field Index
The following example creates an ascending index on the specified field:
$indexName = $collection->createIndex(['<field name>' => 1]);
To learn more about single field indexes, see the Single Field Indexes guide.
Compound Index
The following example creates a compound index of two ascending indexes on the specified fields:
$indexName = $collection->createIndex( ['<field name 1>' => 1, '<field name 2>' => 1] );
To learn more about compound indexes, see the Compound Indexes guide.
Multikey Index
The following example creates an ascending multikey index on the specified array-valued field:
$indexName = $collection->createIndex(['<array field name>' => 1]);
To learn more about multikey indexes, see the Multikey Indexes guide.
Geospatial Index
The following example creates a 2dsphere index on the specified field that has GeoJSON object values:
$indexName = $collection->createIndex( [ '<GeoJSON object field>' => '2dsphere'] );
To learn more about the GeoJSON data type, see GeoJSON Objects in the MongoDB Server manual.
Unique Index
The following example creates an ascending unique index on the specified field:
$indexName = $collection->createIndex(['<field name>' => 1], ['unique' => true]);
Wildcard Index
The following example creates an ascending wildcard index on the collection:
$indexName = $collection->createIndex(['$**' => 1]);
Clustered Index
You can create a clustered index when creating a new collection in a
specified database. The following example creates a new collection with an
ascending clustered index on the _id
field:
$options = [ 'clusteredIndex' => [ 'key' => ['_id' => 1], 'unique' => true ] ]; $database->createCollection('<collection name>', $options);
Text Index
The following example creates a text index on the specified string field:
$indexName = $collection->createIndex(['<field name>' => 'text']);
List Indexes
The following example prints a list of indexes in the specified collection:
foreach ($collection->listIndexes() as $indexInfo) { echo $indexInfo; }
Delete an Index
The following example deletes an index with the specified name:
$collection->dropIndex('<index name>');
To learn more about deleting indexes, see Remove an Index in the Index Considerations and Management guide.
Atlas Search Index Management
The following sections contain code examples that describe how to manage Atlas Search indexes.
Note
Atlas Search Index Management is Asynchronous
The MongoDB PHP Library manages Atlas Search indexes asynchronously. The library methods described in the following sections return the server response immediately, but the changes to your Search indexes take place in the background and might not complete until some time later.
To learn more about Atlas Search indexes, see the Atlas Search Indexes guide.
Create Search Index
The following example creates an Atlas Search index on the specified field:
$indexName = $collection->createSearchIndex( ['mappings' => ['dynamic' => true]], ['name' => '<Search index name>'] );
List Search Indexes
The following example prints a list of Atlas Search indexes in the specified collection:
foreach ($collection->listSearchIndexes() as $indexInfo) { echo toJSON($indexInfo), PHP_EOL; }
Update Search Indexes
The following example updates an existing Atlas Search index with the specified new index definition:
$collection->updateSearchIndex( '<Search index name>', ['mappings' => [ 'dynamic' => false, 'fields' => [ '<string field name>' => [ 'type' => 'string', 'analyzer' => 'lucene.standard' ] ] ]] );
Delete Search Indexes
The following example deletes an Atlas Search index with the specified name:
$collection->dropSearchIndex('<Search index name>');