MongoDB - Java

MongoDB - PHP

MongoDB - Advanced

MongoDB - Useful Resources

MongoDB - PHP - Create Collection



MongoDB provides createCollection() method to create a collection.

Syntax

// select a database
$db = $client->myDb;
echo "<br/>Database myDb selected.";
$collection = $db->createCollection("mycol");
echo "<br/>Collection created succsessfully";

Creating a Collection

To create a collection, we first need to connect to a database and then create the collection as shown below −

<?php
   require __DIR__ . '\vendor\autoload.php';
   try {
	  $uri = "mongodb://localhost:27017";
      // connect to mongodb
      $client = new MongoDB\Client($uri);
      echo "Connection to database successful.";
       // select a database
      $db = $client->myDb;
      echo "<br/>Database myDb selected.";
      $collection = $db->createCollection("mycol");
      echo "<br/>Collection created succsessfully";
   } catch (MongoDB\Driver\Exception\Exception $e) {	   
      echo "Exception:", $e->getMessage(), "\n";
   }
?>

Output

Now, let's compile and run the above program to create a collection in our database myDb.

On executing, the above program gives you the following output.

Connection to database successfully
Database mydb selected
Collection created succsessfully
Advertisements