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

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
Comments
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();
}
}
db.getSiblingDB('Marks').dropDatabase(). So you could simply hardcode these names.