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

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
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With