MongoDB Drop Collection

MongoDB Drop Collection

MongoDB Drop Collection

Dropping a collection in MongoDB permanently removes all documents and the collection itself from the database. This guide will cover how to drop a collection using MongoDB Shell, Node.js (Mongoose), and Compass.

1. Understanding drop() in MongoDB

MongoDB provides the drop() method to delete an entire collection.

CommandDescription
db.collection.drop()Deletes the specified collection from the database.
db.dropDatabase()Deletes the entire database (including all collections).

2. Drop a Collection Using MongoDB Shell

A. Open MongoDB Shell

First, open MongoDB shell:

mongosh

Select the database containing the collection:

use blogDB

B. Drop a Collection

To delete the posts collection:

db.posts.drop()

Response:

true

If the collection does not exist, it returns false.

C. Verify the Collection Is Dropped

Check if the collection still exists:

show collections

If the collection was successfully dropped, it won't be listed.

3. Drop a Collection Using Node.js (Mongoose)

A. Install Mongoose (If Not Installed)

npm install mongoose

B. Connect to MongoDB and Drop Collection

Modify server.js to drop a collection using Mongoose:

const mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/blogDB', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => console.log("✅ Connected to MongoDB")) .catch(err => console.error("❌ Connection Error:", err)); async function dropCollection() { try { await mongoose.connection.db.collection('posts').drop(); console.log("✅ Collection 'posts' dropped successfully"); } catch (error) { console.log("❌ Error dropping collection:", error.message); } finally { mongoose.connection.close(); } } dropCollection();

Run the script:

node server.js

If successful, the console will display:

✅ Collection 'posts' dropped successfully

4. Drop a Collection Using Express.js API

Create an API to drop a collection dynamically.

A. Modify routes/postRoutes.js

const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); // DELETE - Drop the 'posts' collection router.delete('/drop', async (req, res) => { try { await mongoose.connection.db.collection('posts').drop(); res.json({ message: "✅ Collection 'posts' dropped successfully" }); } catch (error) { res.status(400).json({ message: "❌ Error dropping collection", error: error.message }); } }); module.exports = router;

B. Test the API (Using cURL or Postman)

curl -X DELETE http://localhost:3000/api/posts/drop

Example Response:

{ "message": "✅ Collection 'posts' dropped successfully" }

5. Drop a Collection Using MongoDB Compass

If you prefer a graphical interface, use MongoDB Compass:

  1. Open MongoDB Compass and connect to your database.
  2. Select the database (e.g., blogDB).
  3. Find the collection you want to drop (e.g., posts).
  4. Click the "..." (More Options) button next to the collection.
  5. Select Drop Collection and confirm the action.

The collection will be permanently deleted.

6. Summary

Dropped a collection using MongoDB Shell (db.collection.drop()).
Used Mongoose to drop a collection via a script.
Created an Express.js API to drop a collection dynamically.
Used MongoDB Compass for a GUI-based approach.

7. Next Steps

🔹 Drop an entire database using db.dropDatabase().
🔹 Implement authentication to prevent unauthorized deletions.
🔹 Backup collections before dropping them (if needed).

Would you like help implementing backups or authentication? 🚀

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