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

Download the Altoros NoSQL Performance Benchmark 2018. Compare top NoSQL solutions – Couchbase Server v5.5, MongoDB v3.6, and DataStax Enterprise v6 (Cassandra).

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.

Download the whitepaper, Moving From Relational to NoSQL: How to Get Started. We’ll take you step by step through your first NoSQL project.

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 }}