sparkmix
sparkmix

Reputation: 2489

PHP7 MongoDB - create index

I'm moving a php script that create index in mongo from php5 to php7.

I tried to use the following MongoDB\Driver\Command but it returns this error.

Anyone know how to create index to an existing collection?

$index = ['id' => 1, 'user' => 1, 'time' => 1];
$cmd = new MongoDB\Driver\Command([
     'createIndexes' => $collection_name, 
     'indexes' => $index
]);
$mongo_client->executeCommand($mongo_database, $cmd);

PHP Fatal error: Uncaught MongoDB\Driver\Exception\RuntimeException: no such cmd: createIndexes

Upvotes: 0

Views: 2977

Answers (1)

Ivan Viskovic
Ivan Viskovic

Reputation: 61

I am not sure if you solved it already but i have found solution:

 $manager = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
 $command = new MongoDB\Driver\Command([
    "createIndexes" => "collectionName",
    "indexes"       => [[
      "name" => "indexName",
      "key"  => [ "keyName" => 1],
      "ns"   => "databaseName.collectionName",
   ]],
]);
$result = $manager->executeCommand("databaseName", $command);

Credits to: https://github.com/mongodb/mongo-php-driver/issues/170

Also you can add index options like unique or expireAfterSeconds inside:

$command = new MongoDB\Driver\Command([
        "createIndexes" => "collectionName",
        "indexes"       => [[
          "name" => "indexName",
          "key"  => [ "keyName" => 1],
          "ns"   => "databaseName.collectionName",
          "unique" => true,
          // "expireAfterSeconds" => 300
       ]],
    ]);

Upvotes: 3

Related Questions