MongoCollection::deleteIndex

(PECL mongo >=0.9.0)

MongoCollection::deleteIndexDeletes an index from this collection

Description

public array MongoCollection::deleteIndex ( string|array $keys )

This method is identical to:

<?php

public function deleteIndexes($keys) {
  
// toIndexString is a protected method that turns strings, arrays, and objs 
  //into index names
  
$index $this->toIndexString($keys);

  return 
$this->db->command(array("deleteIndexes" => $this->getName(), 
    
"index" => $index);
}

?>

Each index, when created, is given a unique name. This is generally user-set (with MongoCollection::ensureIndex()'s "name" option) or generated by the driver from a combination of key names and directions. This name is then used by MongoCollection::deleteIndex() to remove the function.

Unfortunately, the MongoCollection::ensureIndex() generates slightly different names than the shell and, due to backwards compatibility issues, MongoCollection::deleteIndex() cannot delete custom-named indexes as well. Thus, the best way to delete indexes created in the shell or with custom names is to directly call the deleteIndexes database command.

Thus, if you named an index "superfast query", you could delete it with:

<?php

$db
->command(array("deleteIndexes" => $collection->getName(), "index" => "superfast query");

?>

To find what an index is named, you can query the system.indexes collection of a database and look for the name field.

Parameters

keys

Field or fields from which to delete the index.

Return Values

Returns the database response.

Examples

Example #1 MongoCollection::deleteIndex() example

This example passes the function string and array parameters.

<?php
$m 
= new Mongo();
$c $m->example->indices;

// create an index
$c->ensureIndex(array("i"=>1));

// remove a simple index
$c->deleteIndex("i");


// create a multi-key index
$c->ensureIndex(array("j" => 1"k" => 1));

// remove a multi-key index
$c->deleteIndex(array("j" => 1"k" => 1));
?>
add a note add a note

User Contributed Notes 1 note

up
0
nanhe dot kumar at gmail dot com
6 months ago
<?php
/*
How can delete Index through Index name.
*/
function deleteIndex($db, $collection, $indexName) {
    if (
class_exists("MongoClient")) {
       
$m = new MongoClient();
    } else {
       
$m = new Mongo();
    }
   
$indexes = $m->{$db}->{$collection}->getIndexInfo();
    foreach (
$indexes as $index) {
        if (
$index['name'] === $indexName) {
            return
$m->{$db}->command(array("deleteIndexes" => $this->m->{$db}->{$collection}->getName(), "index" =>$index['key']));
            break;
        }
    }
    return
false;
}   
   
$response=deleteIndex('student','class','roll');
    echo
"<pre>;
    print_r(
$response);
    echo "
</pre>";

?>

Array
(
    [nIndexesWas] => 2
    [ok] => 1
)
To Top