MongoCollection
PHP Manual

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

Описание

public bool MongoCollection::ensureIndex ( string|array $key|keys [, array $options = array() ] )
Внимание

This method is deprecated since version 1.5.0. Please use MongoCollection::createIndex() instead.

This method creates an index on the collection and the specified fields. The key specification can either be just a single field name as string, or an array containing one or more field names with their sort direction.

Список параметров

keys

An array of fields by which to sort the index on. Each element in the array has as key the field name, and as value either 1 for ascending sort, or -1 for descending sort.

options

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

  • "w"

    Смотрите WriteConcerns. Значение по умолчанию для MongoClient является 1.

  • "unique"

    Create a unique index.

    Внимание

    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. Sparse indexing may be used to overcome this, since it will prevent documents without the field from being indexed.

  • "dropDups"

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

  • "sparse"

    Create a sparse index, which only includes documents containing the field. This option is only compatible with single-field indexes.

  • "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.

    This feature is available in MongoDB 2.2+. See » Expire Data from Collections by Setting TTL for more information.

  • "background"

    By default, index creation is a blocking operation and will stop other operations on the database from proceeding until completed. If you specify TRUE for this option, the index will be created in the background while other operations are taking place.

    Внимание

    Prior to MongoDB 2.1.0, the index build operation is not a background build when it replicates to secondaries, irrespective of this option. See » Building Indexes with Replica Sets for more information.

  • "name"

    This option allows you to override the algorithm that the driver uses to create an index name and specify your own. This can be useful if you are indexing many keys and Mongo complains about the index name being too long.

  • "timeout"

    Целое значение, по умолчанию равно MongoCursor::$timeout. Если используются подтвержденные операции записи, то значение обозначает количество миллисекунд, в течение которого клиент будет ожидать ответа от базы данных. Если база данных не ответит в течение указанного периода, то будет брошено исключение MongoCursorTimeoutException.

  • "safe"

    Устарело. Пожалуйста, используйте WriteConcern опцию w.

Возвращаемые значения

Returns an array containing the status of the index creation if the "w" option is set. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Список изменений

Версия Описание
1.3.0 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.

Ошибки

Throws MongoException if the index name is longer than 128 bytes. (Version 1.0.11+)

Бросает исключение MongoCursorException, если установлена опция "w" и запись не удалась.

Бросает исключение MongoCursorTimeoutException, если опция "w" установлена в значение больше единицы и операция занимает более, чем MongoCursor::$timeout миллисекунд. Операция на сервере не прекращается, это таймаут клиента. Операция в MongoCollection::$wtimeout считается в миллисекундах.

Примеры

Пример #1 MongoCollection::ensureIndex() example

<?php

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

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

// create an index on 'y' ascending
$c->ensureIndex(array('y' => 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));

?>

Пример #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"));

?>

Пример #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"));

?>

Смотрите также

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


MongoCollection
PHP Manual