3

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

4
  • Interesting. There appears to be no method to enumerate databases (or their names) in a code-friendly way. There is one for collections, but not databases. Commented Jul 25, 2018 at 17:08
  • if you know the name, it's trivial: db.getSiblingDB('Marks').dropDatabase(). So you could simply hardcode these names. Commented Jul 25, 2018 at 17:09
  • Check it [stackoverflow.com/questions/3366397/… Commented Jul 25, 2018 at 17:11
  • 1
    @SergioTulentsev actually there is a method to do that, it's just not formally documented. Please see my answer below. Commented Jul 27, 2018 at 6:35

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

5

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();
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.