Store a function to delete all db in MongoDb

Deleting everything in a test MongoDb is a common operation for test and dev machine and it is a relative simple operation that I described here. After a little while I got really tired every time to search my gist or into my hd the little script that deletes everything, thus I decided to store it inside the admin db.

The solution is really really simple, just connect to the admin database and register a server side function to delete all databases.

db.system.js.save(
   {
     _id: "DeleteAllDb",
     value : function(db) { 
         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();
            }
        }
      }
   }
)

Once the function is saved, you should see it from a GUI tool like Robo 3T.

DeleteAllDb function stored inside the admin database.

Figure 1: DeleteAllDb function stored inside the admin database.

Now you can simply load all functions from the Shell and execute the new DeleteAllDbFunction.

db.loadServerScripts();
DeleteAllDb(db);

And now you can avoid looking around from the script, just invoke DeleteAllDb(db) function from the shell and you will delete all db, except Admin and Local.

Gian Maria.

Published by

Ricci Gian Maria

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

Leave a Reply

Your email address will not be published.

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