Docs Menu
Docs Home
/ / /
PHP Library Manual
/ /

MongoDB\Collection::createIndex()

On this page

  • Definition
  • Parameters
  • Return Values
  • Errors/Exceptions
  • Examples
  • See Also
MongoDB\Collection::createIndex()

Create an index for the collection.

function createIndex(
array|object $key,
array $options = []
): string
$key : array|object

Specifies the field or fields to index and the index order.

For example, the following specifies a descending index on the username field:

[ 'username' => -1 ]
$options : array

An array specifying the desired options.

The $options parameter accepts both index and command options. A non-exhaustive list of index options follows. For a complete list of index options, refer to the createIndexes command reference in the MongoDB manual.

Index Options (non-exhaustive)

collation
array|object

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the locale field is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.

If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

expireAfterSeconds
integer
Creates a TTL index.
name
string
A name that uniquely identifies the index. By default, MongoDB creates index names based on the key.
partialFilterExpression
array|object
Creates a partial index.
sparse
boolean
Creates a sparse index.
unique
boolean
Creates a unique index.

Command 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.

This option is available since MongoDB 4.4 and will result in an exception at execution time if specified for an older server version.

New in version 1.13.

commitQuorum
string|integer

Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready.

This option accepts the same values for the w field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes.

This is not supported for server versions prior to 4.4 and will result in an exception at execution time if used.

New in version 1.7.

maxTimeMS
integer

The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.

New in version 1.3.

session

Client session to associate with the operation.

New in version 1.3.

writeConcern

Write concern to use for the operation. Defaults to the collection's write concern.

It is not possible to specify a write concern for individual operations as part of a transaction. Instead, set the writeConcern option when starting the transaction.

The name of the created index as a string.

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 extension level (e.g. connection errors).

The following example creates a compound index on the borough and cuisine fields in the restaurants collection in the test database.

<?php
$collection = (new MongoDB\Client)->selectCollection('test', 'restaurants');
$indexName = $collection->createIndex(['borough' => 1, 'cuisine' => 1]);
var_dump($indexName);

The output would then resemble:

string(19) "borough_1_cuisine_1"

The following example adds a partial index on the borough field in the restaurants collection in the test database. The partial index indexes only documents where the borough field exists.

<?php
$collection = (new MongoDB\Client)->selectCollection('test', 'restaurants');
$indexName = $collection->createIndex(
['borough' => 1],
[
'partialFilterExpression' => [
'borough' => ['$exists' => true],
],
]
);
var_dump($indexName);

The output would then resemble:

string(9) "borough_1"

Back

countDocuments()