PHP 和 MongoDB - 建立集合



執行任何操作的第一步是建立一個管理器例項。

// Connect to MongoDB using Manager Instance
$manager = new MongoDB\Driver\Manager("mongodb://:27017");

第二步是準備並執行一條建立集合的命令。

// Create a Command Instance
$createCollection = new MongoDB\Driver\Command(["create" => "sampleCollection"]);

// Execute the command on the database
$cursor = $manager->executeCommand("myDb", $createCollection);

示例

嘗試以下示例在 MongoDB 伺服器上建立一個集合 −

複製並貼上以下示例,作為 mongodb_example.php −

<?php
   try {
      // connect to mongodb
      $manager = new MongoDB\Driver\Manager("mongodb://:27017");

      // Create a Command Instance
      $createCollection = new MongoDB\Driver\Command(["create" => "sampleCollection"]);

      // Execute the command on the database
      $cursor = $manager->executeCommand("myDb", $createCollection);
   
      echo "Collection created.";
   } catch (MongoDB\Driver\Exception\Exception $e) {	   
      echo "Exception:", $e->getMessage(), "\n";
   }
?>

輸出

訪問在 Apache Web 伺服器上部署的 mongodb_example.php 並驗證輸出。

Collection created.
廣告