The following code example shows how to create a MongoDB database using PHP Script.

Using the given server address and other default options, the MongoClient class creates an instance of Mongo. The next statement creates a database with the name ‘Blog’ if it doesn’t exist already. However, if the database is already there, it is selected.

<?php
   // connect to mongodb
   $db_manager = new MongoClient();
	
   echo "Connected!";
   // select a database
   $database = $db_manager->Blog;
	
   echo "<br>Selecting the Blog Database....";
?>

Output

Program to Create a MongoDB database using PHP Script
Program to Create a MongoDB database using PHP Script

As can be seen in the following figure, the GUI client of Mongo, the MongoDB Compass shows the newly created database ‘Blog‘.

The Database Blog shown in the MongoDB Compass
The Database Blog shown in the MongoDB Compass

Further Reading

Getting Started With MongoDB

Working with MongoDB Compass

Create a collection in a MongoDB database in PHP

Insert Documents in a Collection

Show All Documents in a Collection

princites.com