indexes.md 2.78 KB

Indexes

Indexes may be managed via the MongoDB\Collection class, which implements MongoDB's cross-driver Index Management and Enumerating Indexes specifications. This page will demonstrate how to create, list, and drop indexes using the library. General information on how indexes work in MongoDB may be found in the MongoDB manual.

Creating Indexes

Indexes may be created via the createIndex() and createIndexes() methods. The following example creates an ascending index on the "state" field:

<?php

$collection = (new MongoDB\Client)->demo->zips;

$result = $collection->createIndex(['state' => 1]);

var_dump($result);

Creating an index will return its name, which is automatically generated from its specification (i.e. fields and orderings). The above example would output something similar to:

string(7) "state_1"

Enumerating Indexes

Information about indexes in a collection may be obtained via the listIndexes() method, which returns an iterator of MongoDB\Model\IndexInfo objects. The following example lists all indexes in the "demo.zips" collection:

<?php

$collection = (new MongoDB\Client)->demo->zips;

foreach ($collection->listIndexes() as $indexInfo) {
    var_dump($indexInfo);
}

The above example would output something similar to:

object(MongoDB\Model\IndexInfo)#10 (4) {
  ["v"]=>
  int(1)
  ["key"]=>
  array(1) {
    ["_id"]=>
    int(1)
  }
  ["name"]=>
  string(4) "_id_"
  ["ns"]=>
  string(9) "demo.zips"
}
object(MongoDB\Model\IndexInfo)#13 (4) {
  ["v"]=>
  int(1)
  ["key"]=>
  array(1) {
    ["state"]=>
    int(1)
  }
  ["name"]=>
  string(7) "state_1"
  ["ns"]=>
  string(9) "demo.zips"
}

Dropping Indexes

Indexes may be dropped via the dropIndex() and dropIndexes() methods. The following example drops a single index by its name:

<?php

$collection = (new MongoDB\Client)->demo->zips;

$result = $collection->dropIndex('state_1');

var_dump($result);

The above example would output something similar to:

object(MongoDB\Model\BSONDocument)#11 (1) {
  ["storage":"ArrayObject":private]=>
  array(2) {
    ["nIndexesWas"]=>
    int(2)
    ["ok"]=>
    float(1)
  }
}