Docs Menu

Docs HomePHP Library Manual

MongoDB\Collection::createSearchIndexes()

On this page

  • Definition
  • Parameters
  • Return Values
  • Errors/Exceptions
  • Behavior
  • Examples
  • See Also

New in version 1.17.

MongoDB\Collection::createSearchIndexes()

Create one or more Atlas Search indexes for the collection.

function createSearchIndexes(
array $indexes,
array $options = []
): string

This command can only be run on a deployment hosted on MongoDB Atlas and requires an Atlas cluster tier of at least M10. A Local Atlas Deployment can also be used for development.

$indexes : array

Array of documents describing the indexes to create.

A required definition document field describes the index to create. For details on definition syntax, see Search Index Definition Syntax.

An optional name string field specifies the name of the search index to create. You cannot create multiple indexes with the same name on a single collection. If you do not specify a name, the index is named "default".

$options : array

An array specifying the desired options.

Name
Type
Description
comment
mixed

Enables users to specify an arbitrary comment to help trace the operation through the database profiler, currentOp output, and logs.

The names of the created Atlas Search indexes as an array of strings.

MongoDB\Exception\UnsupportedException if options are used and not supported by the selected server (e.g. collation, readConcern, writeConcern).

MongoDB\Exception\InvalidArgumentException for errors related to the parsing of parameters or options.

MongoDB\Driver\Exception\RuntimeException for other errors at the driver level (e.g. connection errors).

Atlas Search indexes are managed asynchronously. After creating or updating an index, you can periodically execute MongoDB\Collection::listSearchIndexes() and check the queryable output field to determine whether it is ready to be used.

The following example creates an Atlas Search index using dynamic mappings to index all document fields containing supported data types.

<?php
$collection = (new MongoDB\Client)->selectCollection('test', 'articles');
$indexNames = $collection->createSearchIndexes(
[
[
'name' => 'test-search-index',
'definition' => ['mappings' => ['dynamic' => true]],
],
]
);
var_dump($indexNames);

The output would then resemble:

array(1) {
[0]=>
string(17) "test-search-index"
}
← MongoDB\Collection::createSearchIndex()