8288分类目录 8288分类目录 8288分类目录
  当前位置:海洋目录网 » 站长资讯 » 站长资讯 » 文章详细 订阅RssFeed

PHP - Manual: MongoCollection::createIndex

来源:网络转载 浏览:30147次 时间:2024-03-28
MongoCollection::deleteIndex » « MongoCollection::createDBRef
  • PHP 手册
  • 函数参考
  • 数据库扩展
  • 针对各数据库系统对应的扩展
  • Mongo
  • 核心类
  • MongoCollection

MongoCollection::createIndex

(PECL mongo >=1.5.0)

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

说明

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

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.

参数

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. We pass all given options straight to the server, but a non-exhaustive list of 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.

    Note:

    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.

    Note:

    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.

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

  • "w"

    See WriteConcerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

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

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

  • "safe"

    Deprecated. Please use the WriteConcern w option.

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

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

返回值

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.

Throws MongoCursorException if the "w" option is set and the write fails.

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.

范例

Example #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));

?>

Example #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'));

?>

Example #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'));

?>

参见

  • MongoCollection::deleteIndex() - Deletes an index from this collection
  • MongoCollection::deleteIndexes() - 删除集合的所有索引
  • The MongoDB » index and » index type documentation.
add a note

User Contributed Notes 2 notes

up down 4 bosuy dot misha at gmail dot com2 years ago 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);
up down 0 sNICkers2 years ago 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);
add a note

官方地址:https://www.php.net/manual/en/mongocollection.createindex.php

  推荐站点

  • At-lib分类目录At-lib分类目录

    At-lib网站分类目录汇集全国所有高质量网站,是中国权威的中文网站分类目录,给站长提供免费网址目录提交收录和推荐最新最全的优秀网站大全是名站导航之家

    www.at-lib.cn
  • 中国链接目录中国链接目录

    中国链接目录简称链接目录,是收录优秀网站和淘宝网店的网站分类目录,为您提供优质的网址导航服务,也是网店进行收录推广,站长免费推广网站、加快百度收录、增加友情链接和网站外链的平台。

    www.cnlink.org
  • 35目录网35目录网

    35目录免费收录各类优秀网站,全力打造互动式网站目录,提供网站分类目录检索,关键字搜索功能。欢迎您向35目录推荐、提交优秀网站。

    www.35mulu.com
  • 就要爱网站目录就要爱网站目录

    就要爱网站目录,按主题和类别列出网站。所有提交的网站都经过人工审查,确保质量和无垃圾邮件的结果。

    www.912219.com
  • 伍佰目录伍佰目录

    伍佰网站目录免费收录各类优秀网站,全力打造互动式网站目录,提供网站分类目录检索,关键字搜索功能。欢迎您向伍佰目录推荐、提交优秀网站。

    www.wbwb.net