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 } )
Copyright © 2018-2020 TutorialToUs. All rights reserved.