How to drop a database in MongoDB using PHP?

by lindsey.homenick , in category: PHP Databases , a year ago

How to drop a database in MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , a year ago

@lindsey.homenick 

To drop a database in MongoDB using PHP, you can make use of the MongoDB PHP driver. Here's an example of how you can drop a database:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?php

// Include the MongoDB library
require 'vendor/autoload.php';

// Connect to MongoDB server
$mongoClient = new MongoDBClient('mongodb://localhost:27017');

// Select the database you want to drop
$databaseName = 'your_database_name';

// Drop the database
$mongoClient->dropDatabase($databaseName);

echo "Database '$databaseName' dropped successfully.";

?>


Make sure you have the MongoDB PHP driver installed and included in your project. You can install it using Composer by adding the following line to your composer.json file:

1
2
3
4
5
{
    "require": {
        "mongodb/mongodb": "^1.8"
    }
}


After saving the composer.json file, run the following command to install the MongoDB PHP driver:

1
composer install


Replace 'your_database_name' with the name of the database you want to drop. Once you run this script, the specified database will be dropped, and you will see a success message. Please exercise caution when using the dropDatabase method as it irreversibly deletes the entire database and all its collections and data.