English | 简体中文 | 繁體中文
查询

Collection::createIndex()函数—用法及示例

「 在MongoDB集合中创建索引,以便提高查询效率 」


函数名称:Collection::createIndex()

适用版本:MongoDB版本3.2及以上版本

函数说明:Collection::createIndex()函数用于在MongoDB集合中创建索引,以便提高查询效率。

参数:

  1. keys:一个关联数组,指定要创建索引的字段和排序顺序。键是字段名,值是1表示升序,-1表示降序。
  2. options(可选):一个关联数组,指定索引创建的可选参数。

用法示例:

<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$collection = new MongoDB\Collection($manager, "mydb", "mycollection");

// 创建一个单字段的升序索引
$keys = ['username' => 1];
$options = ['name' => 'username_index'];
$result = $collection->createIndex($keys, $options);

// 创建一个复合索引(多个字段)并设定唯一性和背景创建模式
$keys = ['username' => 1, 'email' => 1];
$options = [
   'name' => 'username_email_index',
   'unique' => true,
   'background' => true
];
$result = $collection->createIndex($keys, $options);

// 创建一个文本索引,适用于全文搜索
$keys = ['description' => 'text'];
$result = $collection->createIndex($keys);

// 创建一个地理位置索引
$keys = ['location' => '2dsphere'];
$result = $collection->createIndex($keys);

// 创建一个哈希索引
$keys = ['password' => 'hashed'];
$result = $collection->createIndex($keys);
?>

注意事项:

  1. 在创建索引时可以指定索引的名称,以便后续查询和管理索引。
  2. 可以通过可选参数设置索引的唯一性、背景创建模式、过期时间等属性。
  3. 可以创建多个索引,以满足不同查询需要。
  4. 索引创建可能会对数据库性能产生一定影响,特别是在大量数据插入期间。
  5. 不同类型的索引可以提供不同的查询优化能力,请根据实际需求选择适当的索引类型。
补充纠错
热门PHP函数
分享链接