Droping Collection And Droping Database in MongoDB
Droping Collection
db.collectionname.drop() removes a collection from the database. The method also removes any indexes associated with the dropped collection.
Syntax:
db.collection.drop()
Returns:
- true when successfully drops a collection.
- false when collection to drop does not exist.
Example:
Drop the 'users' collection
>db.users.drop()
Output:-
true
Again Drop the 'users' collection
>db.users.drop()
Output:-
false
'users' collection already droped in the above example so now it will returns false as of inexistense
Note
- db.collection.drop() method obtains a write lock on the affected database and will block other operations until it has completed.
- In some cases we need to delete the indexes manually to drop
collection so check dropIndex pary
Droping Database
The dropDatabase command drops the current database, deleting the associated data files. To execute this command first we need to switch to that database and then need to run that command as
Syntax:-
db.dropDatabase()
or
db.runCommand( { dropDatabase: 1 } )
Example:
Drop the 'temp' database using dropDatabase() method
use temp; db.dropDatabase()
Drop the 'local' database using runCommand() method
use local; db.runCommand( { dropDatabase: 1 } )