Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Store a Function to Delete All Databases in MongoDB [Code Snippet]

DZone's Guide to

Store a Function to Delete All Databases in MongoDB [Code Snippet]

I got really tired of searching for the little script that deletes everything every time I needed it and decided to store it inside the admin database.

· Database Zone ·
Free Resource

Databases are better when they can run themselves. CockroachDB is a SQL database that automates scaling and recovery. Check it out here.

Deleting everything in a test MongoDB is a common operation for test and dev machines. It's a relatively simple operation that I have described here. After a little while, I got really tired of searching for the little script that deletes everything every time I needed it. Thus, I decided to store it inside the admin database.

The solution is 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 DeleteAllDb function.

db.loadServerScripts(); 
DeleteAllDb(db); 

Now, you can avoid moving away from the script; just invoke the DeleteAllDb(db) function from the shell and you will delete all databases, except Admin and Local.

Databases should be easy to deploy, easy to use, and easy to scale. If you agree, you should check out CockroachDB, a scalable SQL database built for businesses of every size. Check it out here. 

Topics:
database ,mongodb ,deleting databases

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}