PHP & MongoDB - Create Collection



Steps to Create a Collection

First step to do any operation is to create a MongoDB Client instance.

$uri = "mongodb://localhost:27017";
// connect to mongodb
$client = new MongoDB\Client($uri);

Second step is to prepare and execute a command to create a collection.

// select a database
$db = $client->myDb;

// execute a command
$cursor=$db->command(array('create' => 'sampleCollection'));

Example - Create a MongoDB Collection

Try the following example to create a collection in a MongoDB database −

index.php

<?php
   require __DIR__ . '\vendor\autoload.php';
   $uri = "mongodb://localhost:27017";

   // connect to mongodb
   $client = new MongoDB\Client($uri);

   // select a database
   $db = $client->myDb;

   // execute a command
   $cursor=$db->command(array('create' => 'sampleCollection'));
      
   echo "Collection created."
?>

Output

Access the index.php deployed on apache web server and verify the output.

Collection created.
Advertisements