Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop all databases in MongoDB?

I have a list of databases in my MongoDB. How to delete all databases except local, admin, and config?
enter image description here

like image 978
Ponabenthur Vithushan Avatar asked Dec 17 '25 12:12

Ponabenthur Vithushan


2 Answers

You can use the getDBNames() method in the mongo shell.

This method must be called from the Mongo() instance. Unfortunately I don't think the getDBNames() method is documented.

After getting the database names, you can then loop through them to drop the unwanted ones using something like:

Mongo().getDBNames().forEach(function(x) {
  // loop through all the database names
  if (['admin', 'config', 'local'].indexOf(x) < 0) {
    // drop database if it's not admin, config, or local
    Mongo().getDB(x).dropDatabase();
  }
})

For example:

> show dbs
admin   0.000GB
config  0.000GB
local   0.001GB
test    0.000GB
test2   0.000GB
test3   0.000GB

> Mongo().getDBNames().forEach(function(x) {
...   if (['admin', 'config', 'local'].indexOf(x) < 0) {
...     Mongo().getDB(x).dropDatabase();
...   }
... })

> show dbs
admin   0.000GB
config  0.000GB
local   0.001GB
like image 139
kevinadi Avatar answered Dec 19 '25 05:12

kevinadi


I fixed this issue using solution from this tutorial

I ran this code in my mongo shell:

var dbs = db.getMongo().getDBNames()
for(var i in dbs){
    db = db.getMongo().getDB( dbs[i] );
    if (db.getName() !== 'admin' && db.getName() !== 'local' && db.getName() !== 'config') 
    {
        print( "dropping db " + db.getName() );  
        db.dropDatabase();
    }
}
like image 37
Al Fahad Avatar answered Dec 19 '25 05:12

Al Fahad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!