MongoDB Delete Database

MongoDB Delete Database

MongoDB Delete Database

Deleting a database in MongoDB is simple but permanent, so proceed with caution. This guide covers how to delete a MongoDB database using MongoDB Shell, Node.js (Mongoose), and MongoDB Compass.

1. Delete a Database Using MongoDB Shell

A. Open MongoDB Shell

Start the MongoDB shell:

mongosh

B. Select the Database to Delete

use blogDB

C. Drop the Database

db.dropDatabase()

Example Output:

{ "dropped": "blogDB", "ok": 1 }

This confirms that blogDB has been deleted.

D. Verify the Deletion

show dbs

Expected Output:

admin 0.000GB config 0.000GB local 0.000GB

If blogDB is missing, it was successfully deleted.

2. Delete a Database Using Node.js (Mongoose)

A. Install Mongoose (If Not Installed)

npm install mongoose

B. Create a Script to Delete the Database

Create deleteDatabase.js:

const mongoose = require('mongoose'); const databaseURL = 'mongodb://127.0.0.1:27017/blogDB'; async function deleteDatabase() { try { const conn = await mongoose.connect(databaseURL, { useNewUrlParser: true, useUnifiedTopology: true }); await conn.connection.dropDatabase(); console.log("✅ Database 'blogDB' deleted successfully."); conn.connection.close(); } catch (error) { console.error("❌ Error deleting database:", error.message); } } deleteDatabase();

C. Run the Script

node deleteDatabase.js

Expected Output:

Database 'blogDB' deleted successfully.

3. Delete a Database Using MongoDB Compass

If you prefer a graphical interface, follow these steps:

  1. Open MongoDB Compass and connect to your server.
  2. Locate the database name (e.g., blogDB).
  3. Click on the trash icon or right-click → Drop Database.
  4. Confirm the deletion in the pop-up window.

✅ The database will be permanently removed.

4. Summary

Deleted a database using MongoDB Shell (dropDatabase()).
Used Mongoose to drop a database programmatically.
Removed a database using MongoDB Compass GUI.

5. Next Steps

🔹 Schedule automatic backups before deleting databases.
🔹 Use authentication to prevent accidental deletions.
🔹 Monitor database size and optimize storage.

Would you like help setting up database backups? 🚀

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close