MongoDB drop every database

Try this command:

mongo --quiet --eval 'db.getMongo().getDBNames().forEach(function(i){db.getSiblingDB(i).dropDatabase()})'

you can create a javascript loop that do the job and then execute it in the mongoconsole.

var dbs = db.getMongo().getDBNames()
for(var i in dbs){
    db = db.getMongo().getDB( dbs[i] );
    print( "dropping db " + db.getName() );
    db.dropDatabase();
}

save it to dropall.js and then execute:

mongo dropall.js

db
  .getMongo()
  .getDBNames()
  .filter(n => !['admin','local','config'].includes(n))
  .forEach(dname =>
    db
      .getMongo()
      .getDB(dname)
      .dropDatabase()
  )
;
db.getMongo().getDBNames().filter(n => !['admin','local','config'].includes(n)).forEach(dname => db.getMongo().getDB(dname).dropDatabase());

This drops all DBs but preserves MongoDB's internal collections.


You can also do this with a simple mongo command:

db.adminCommand("listDatabases").databases.forEach( function (d) {
    if (d.name != "local" && d.name != "admin"  && d.name != "apiomat"  && d.name != "config")
        db.getSiblingDB(d.name).dropDatabase();
 })

Tags:

Mongodb