Last 5.3 release ever available: PHP 5.3.29 - 5.3 now EOL

MongoCollection::ensureIndex

(PECL mongo >=0.9.0)

MongoCollection::ensureIndex Creates an index on the given field(s), or does nothing if the index already exists

Description

public bool MongoCollection::ensureIndex ( array $keys [, array $options ] )

A unique index cannot be created on a field if multiple existing documents do not contain the field. The field is effectively NULL for these documents and thus already non-unique.

Parameters

keys

Field or fields to use as index.

options

This parameter is an associative array of the form array("optionname" => <boolean>, ...). Currently supported options are:

  • "unique"

    Create a unique index.

  • "dropDups"

    If a unique index is being created and duplicate values exist, drop all but one duplicate value.

  • "background"

    If you are using MongoDB version 1.3.2+, you can create indexes in the background while other operations are taking place. By default, index creation happens synchronously. If you specify TRUE with this option, index creation will be asynchronous.

  • "safe"

    Starting with driver version 1.0.4, you can specify a boolean value for checking if the index creation succeeded. The driver will throw a MongoCursorException if index creation failed.

    If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw and exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).

    If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.

  • "name"

    After driver version 1.0.4 (NOT including 1.0.4) you can specify an index name. This can be useful if you are indexing many keys and Mongo complains about the index name being too long.

  • "timeout"

    Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Return Values

Returns TRUE.

Changelog

Version Description
1.2.0 Added timeout option.
1.0.11 "safe" will trigger master failover, if necessary.
1.0.11 MongoException will be thrown if index name (either generated or set) is longer than 128 bytes.
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. (Version 1.0.11+)

Throws MongoCursorException if the "safe" option is set and the index creation fails.

Throws MongoCursorTimeoutException if the "safe" option is set 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.

Examples

Example #1 MongoCollection::ensureIndex() example

<?php

$c 
= new MongoCollection($db'foo');

// create an index on 'x' ascending
$c->ensureIndex(array('x' => 1));

// create an index on 'z' ascending and 'zz' descending
$c->ensureIndex(array('z' => 1'zz' => -1));

// create a unique index on 'x'
$c->ensureIndex(array('x' => 1), array("unique" => true));

?>

Example #2 Drop duplicates example

<?php

$collection
->insert(array("username" => "joeschmoe"));
$collection->insert(array("username" => "joeschmoe"));

/*
 * index creation fails, you can't create a unique index on a key with 
 * non-unique values
 */
$collection->ensureIndex(array("username" => 1), array("unique" => 1));

/*
 * index creation succeeds: one of the documents is removed from the collection
 */
$collection->ensureIndex(array("username" => 1), array("unique" => 1"dropDups" => 1));

/* 
 * now we have a unique index, more inserts with the same username (such as the
 * one below) will fail
 */
$collection->insert(array("username" => "joeschmoe"));

?>

Example #3 Geospatial Indexing

Mongo supports geospatial indexes, which allow you to search for documents near a given location or within a shape. For example, to create a geospatial index on the "loc" field:

<?php

$collection
->ensureIndex(array("loc" => "2d"));

?>

See Also

MongoDB core docs on » vanilla indexes and » geospatial indexes.

add a note add a note

User Contributed Notes 2 notes

up
0
mcuadros at gmail dot com
1 year ago
Ensuring a text index, needed by text search command.

<?php
$collection
->ensureIndex(
    array(
       
'title' => 'text',
       
'desc' => 'text',
    ),
    array(
       
'name' => 'ExampleTextIndex',
       
'weights' => array(
           
'title' => 100,
           
'desc' => 30,
        )
    )
);
up
0
alan dot lake at lakeinfoworks dot com
3 years ago
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.
To Top