簡體   English   中英

PHP7 MongoDB-創建索引

[英]PHP7 MongoDB - create index

我正在將在mongo中創建索引的php腳本從php5遷移到php7。

我嘗試使用以下MongoDB \\ Driver \\ Command,但它返回此錯誤。

有人知道如何為現有集合創建索引嗎?

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

PHP致命錯誤:未捕獲的MongoDB \\ Driver \\ Exception \\ RuntimeException:無此類cmd:createIndexes

我不確定你是否已經解決了,但是我找到了解決方案:

 $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);

歸功於: https : //github.com/mongodb/mongo-php-driver/issues/170

您也可以在其中添加索引選項,例如uniqueexpireAfterSeconds

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM