How can you Drop a Collection in MongoDB?
In MongoDB, dropping a collection can be described as dropping the entire table in RDBMS that contains different attributes. In MongoDB, you have documents contained inside it. Therefore, the entire group of documents will be deleted if you drop the collection inside which it is stored. To drop an existing collection in the database, you can follow the syntax as shown below:
There are two collections named MyfirstCollection and MysecondCollection stored in MyDB Database. Moving ahead, you want to delete MysecondCollection from MyDB. So, to perform this following task you can follow the code as below:
- The above collection will be dropped only when you are in the Database of which this collection is a part. Here, in this case, it is MyDB.
- In the above output:
- The first show collections command is used to show all collections present in the current database
- Then, db.MysecondCollection.drop() is used to drop collection named MysecondCollection.
- Now, the show collection will display all the collections except the deleted one i.e MysecondCollection.