3

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

kevinadi
  • 13,365
  • 3
  • 33
  • 49
  • 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. – Sergio Tulentsev Jul 25 '18 at 17:08
  • if you know the name, it's trivial: `db.getSiblingDB('Marks').dropDatabase()`. So you could simply hardcode these names. – Sergio Tulentsev Jul 25 '18 at 17:09
  • Check it [https://stackoverflow.com/questions/3366397/delete-everything-in-a-mongodb-database] – Pranta Saha Jul 25 '18 at 17:11
  • 1
    @SergioTulentsev actually there is a method to do that, it's just not formally documented. Please see my answer below. – kevinadi Jul 27 '18 at 06:35

2 Answers2

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
kevinadi
  • 13,365
  • 3
  • 33
  • 49
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') 
    {
        print( "dropping db " + db.getName() );  
        db.dropDatabase();
    }
}
Al Fahad
  • 2,378
  • 5
  • 28
  • 37