MongoCollection::createIndex

(PECL mongo >=1.5.0)

MongoCollection::createIndex Creates an index on the specified field(s) if it does not already exist.

Описание

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

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

Замечание:

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.

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

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.

    Замечание:

    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.

  • "dropDups"

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

    Внимание

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

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

    Замечание:

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

  • "name"

    A optional name that uniquely identifies the index.

    Замечание:

    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.

  • "socketTimeoutMS"

    Integer, defaults to MongoCursor::$timeout. If acknowledged writes are used, 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.

The following option may be used with MongoDB 2.6+:

  • "maxTimeMS"

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

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

The following options are deprecated and should no longer be used:

  • "safe"

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

  • "timeout"

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

  • "wtimeout"

    Время ожидания подтверждения WriteConcern. По умолчанию составляет 10000 миллисекунд для класса MongoClient

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

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().

Ошибки

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

Throws MongoDuplicateKeyException if the server could not create the unique index due to conflicting documents.

Throws MongoResultException if the server could not create the index due to an error.

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

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

Примеры

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

<?php

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

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

// create a unique index on 'y'
$c->createIndex(array('y' => 1), array('unique' => true));

// create a compound index on 'za' ascending and 'zb' descending
$c->createIndex(array('za' => 1'zb' => -1));

?>

Пример #2 Geospatial Indexing

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

<?php

$collection
->createIndex(array('loc' => '2dsphere'));

?>

Пример #3 Drop duplicates example

<?php

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

/* Index creation fails, since you cannot create a unique index on a field when
 * duplicates exist.
 */
$collection->createIndex(array('username' => 1), array('unique' => 1));

/* MongoDB will one of the conflicting documents and allow the unique index to
 * be created.
 */
$collection->createIndex(array('username' => 1), array('unique' => 1'dropDups' => 1));

/* We now have a unique index and subsequent inserts with the same username will
 * fail.
 */
$collection->insert(array('username' => 'joeschmoe'));

?>

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

Коментарии

Create index using MongoDB\Driver

$query = new \MongoDB\Driver\Query(['createIndex' => ['my_column' => 1]], []);
$manager = new \MongoDB\Driver\Manager($mongo_connection)
$manager->executeQuery('my_db.my_collection', $query);
2016-07-12 00:47:59
http://php5.kiev.ua/manual/ru/mongocollection.createindex.html
Автор:
For PHP 7.x
Create index using MongoDB\Driver

$command = new \MongoDB\Driver\Command([
    'createIndexes' => 'my_collection_name',
    'indexes' => [[
        'name' => 'my_index_name',
        'key'  => ['my_field_name' => 1]
    ]]
]);

$instance = new \MongoDB\Driver\Manager('mongodb://127.0.0.1:27017');
$instance->executeCommand('my_db_name', $command);
2017-05-22 08:50:08
http://php5.kiev.ua/manual/ru/mongocollection.createindex.html

    Поддержать сайт на родительском проекте КГБ