Description

Creates an index on the specified field(s) if it does not already exist.
Fields may be indexed with a direction (e.g. ascending or descending) or a
special type (e.g. text, geospatial, hashed).

Note:

This method will use the
» createIndexes
database command when communicating with MongoDB 2.6+. For previous database
versions, the method will perform an insert operation on the
special system.indexes collection.

Parameters

keys

An array specifying the index's fields as its keys. For each field, the
value is either the index direction or
» index type.
If specifying direction, specify 1 for ascending or
-1 for descending.

options

An array of options for the index creation. Currently available options
include:

"unique"

Specify TRUE to create a unique index. The default value is FALSE. This option applies only to ascending/descending indexes.

Note:

When MongoDB indexes a field, if a document does not have a value for the field, a NULL value is indexed. If multiple documents do not contain a field, a unique index will reject all but the first of those documents. The "sparse" option may be used to overcome this, since it will prevent documents without the field from being indexed.

"sparse"

Specify TRUE to create a sparse index, which only indexes documents containing a specified field. The default value is FALSE.

"expireAfterSeconds"

The value of this option should specify the number of seconds after which a document should be considered expired and automatically removed from the collection. This option is only compatible with single-field indexes where the field will contain MongoDate values.

By default, the driver will generate an index name based on the index's field(s) and ordering or type. For example, a compound index array("x" => 1, "y" => -1) would be named "x_1_y_-1" and a geospatial index array("loc" => "2dsphere") would be named "loc_2dsphere". For indexes with many fields, it is possible that the generated name might exceed MongoDB's » limit for index names. The "name" option may be used in that case to supply a shorter name.

"background"

Builds the index in the background so that building an index does not block other database activities. Specify TRUE to build in the background. The default value is FALSE.

Warning

Prior to MongoDB 2.6.0, index builds on secondaries were executed as foreground operations, irrespective of this option. See » Building Indexes with Replica Sets for more information.

"socketTimeoutMS"

This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

The following option may be used with MongoDB 2.6+:

"maxTimeMS"

Specifies a cumulative time limit in milliseconds for processing the operation on the server (does not include idle time). If the operation is not completed by the server within the timeout period, a MongoExecutionTimeoutException will be thrown.

The following options may be used with MongoDB versions before 2.8:

"dropDups"

Specify TRUE to force creation of a unique index where the collection may contain duplicate values for a key. MongoDB will index the first occurrence of a key and delete all subsequent documents from the collection that contain a duplicate value for that key. The default value is FALSE.

Warning

"dropDups" may delete data from your database. Use with extreme caution.

Note:

This option is not supported on MongoDB 2.8+. Index creation will fail if the collection contains duplicate values.

This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

Return Values

Returns an array containing the status of the index creation. The array
contains whether the operation succeeded ("ok"), the
number of indexes before and after the operation
("numIndexesBefore" and
"numIndexesAfter"), and whether the collection that the
index belongs to has been created
("createdCollectionAutomatically"). If the index already
existed and did not need to be created, a "note" field may
be present in lieu of "numIndexesAfter".

With MongoDB 2.4 and earlier, a status document is only returned if the
write concern is at least
1. Otherwise, TRUE is returned. The fields in the status
document are different, except for the "ok" field, which
signals whether the index creation was successful. Additional fields are
described in the documentation for
MongoCollection::insert().

Changelog

Version

Description

1.5.0

Renamed the "wtimeout" option to
"wTimeoutMS". Emits
E_DEPRECATED when "wtimeout" is
used.

Renamed the "timeout" option to
"socketTimeoutMS". Emits
E_DEPRECATED when "timeout" is
used.

Emits E_DEPRECATED when "safe"
is used.

1.3.4

Added "wtimeout" option.

1.3.0

Added "w" option.

The options parameter no longer accepts a
boolean to signify a unique index. Instead, this now has to be done
with array('unique' => true).

1.2.11

Emits E_DEPRECATED when
options is scalar.

1.2.0

Added "timeout" option.

1.0.11

The "safe" option will trigger a primary failover,
if necessary.

MongoException will be thrown if the index name
(either generated or set) is longer than 128 bytes.

1.0.5

Added the "name" option to override index name
creation.

1.0.2

Changed options parameter from boolean to array.
Pre-1.0.2, the second parameter was an optional boolean value specifying
a unique index.

Errors/Exceptions

Throws MongoException if the index name is longer
than 128 bytes, or if the index specification is not an array.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

The statement <?php$c->ensureIndex(array('x' => 1), array("unique" => true));?>will prevent a document with a duplicate key ('x') from being added to the connection, but will not throw an exception. To cause an exception to be thrown, use the "safe"=>true option in the insert statement.