Thursday, 28 November 2013

Javascript to flushout MongoDB databases

Here is a javascript that flushes out data from multiple MongoDB databases. You will not need to open each database and use the command
db.collectionName.remove
on each collection.

Here is the script

getting all mongoDB databases
var dbs = db.getMongo().getDBNames();
 If you want to flushout some specifice databases' data, then add them to an array
var dbs = ["DB1","DB2","DB3","DB4"];
for(var i in dbs){
    db = db.getMongo().getDB( dbs[i] );
    print( "Using Database ==> " + db.getName() );
   
if you want to completely drop the database then just use following one line 
//db.dropDatabase();
if you don't want to drop database and just want to remove data from collection, use following code, it will not remove the indexes or username and password if set for database
    db.getCollectionNames().forEach(function(collection) {
    if(collection != 'system.indexes' && collection != 'system.users') {
    print("Removing Data from collection ==> :" +collection);
        db.getCollection(collection).remove();
    }
  });
}

 Save the script as a .js file (e.g. flushdbs.js). you can run the script with following command
mongo < /path/to/script/flushdbs.js

or start mongodb and enter

> load("/path/to/script/flushdbs.js")




No comments:

Post a Comment