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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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.

1
2
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.