Delete all mongo db except admin and local

When you develop with mongo, sometimes you simply need to delete all database quickly because you need to start from scratch. Using shell is really simple, because this gist  does exactly what you need.

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

This snippet is a little bit smarter than deleting everything, because it keeps safe Local and Admin database, and this will preserve users of the database. I always suggest people to develop with authentication enabled, it is a good way to avoid forgetting to secure your production mongo installation and exposing your data at risk.

If you simply delete ALL databases or delete data directory, you will lose users of the database, as well as any information that is stored in admin or local db.

The script is super simple, you can use the getDBNames() function to grab a list of all database names, then you can iterate for each database doing what you want. In this example I simply check the name of the db, and if the db name is different from local or admin, I simply drop it.

The very same script can be used to delete all collection named logs from all databases, or you can simply decide to delete all database with a name that starts with a specific string.

var dbs = db.getMongo().getDBNames()
for(var i in dbs){
    db = db.getMongo().getDB( dbs[i] );
    if (db.getName().startsWith('blah')) 
    {
        print( "dropping db " + db.getName() );  
        db.dropDatabase();
    }
}

The script is almost the same.

Gian Maria.

Published by

Ricci Gian Maria

.Net programmer, User group and community enthusiast, programmer - aspiring architect - and guitar player :). Visual Studio ALM MVP

One thought on “Delete all mongo db except admin and local”

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.