Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to delete a table from MongoDB database?
In MongoDB, collections are equivalent to tables in relational databases. To delete a collection (table) from a MongoDB database, use the drop() method, which removes the entire collection and all its documents permanently.
Syntax
db.collectionName.drop()
Create Sample Data
Let us first create a collection with some sample documents ?
db.deleteTableDemo.insertMany([
{"Name": "Chris", "Age": 23},
{"Name": "Carol", "Age": 21},
{"Name": "David", "Age": 24}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ccfb705140b992277dae0e6"),
ObjectId("5ccfb70c140b992277dae0e7"),
ObjectId("5ccfb714140b992277dae0e8")
]
}
Example: Display Collection Data
Display all documents from the collection to verify it exists ?
db.deleteTableDemo.find().pretty()
{
"_id": ObjectId("5ccfb705140b992277dae0e6"),
"Name": "Chris",
"Age": 23
}
{
"_id": ObjectId("5ccfb70c140b992277dae0e7"),
"Name": "Carol",
"Age": 21
}
{
"_id": ObjectId("5ccfb714140b992277dae0e8"),
"Name": "David",
"Age": 24
}
Example: Delete the Collection
Now delete the entire collection using the drop() method ?
db.deleteTableDemo.drop()
true
The return value true confirms that the collection was successfully deleted.
Verify Deletion
You can verify the collection no longer exists by listing all collections ?
show collections
The deleteTableDemo collection will no longer appear in the list.
Conclusion
The drop() method permanently removes a collection and all its documents from MongoDB. It returns true if successful or false if the collection doesn't exist.
