107

I would like to know if there're a command to drop every databases from my MongoDB?

I know if I want to drop only one datatable, I just need to type the name of the database like the code below but I dont want to have to specify it.

mongo DB_NAME --eval 'db.dropDatabase();'
0

10 Answers 10

158

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
5
  • 14
    var mongo = db.getMongo(); mongo.getDBNames().forEach(function (dbname) { var db = mongo.getDB(dbname); db.dropDatabase(); });
    – tjmehta
    Apr 24, 2013 at 2:13
  • 4
    You could also just copy paste above code and type it on mongo console. May 19, 2015 at 14:05
  • 4
    This droped my system databases (Mongo Version 2.4.3). I had to restart the mongodb process to make it work again. Sep 2, 2015 at 7:11
  • 13
    I think when someone wants to drop their databases they aren't wanting to drop the mongo internal databases like admin and local. Apr 21, 2016 at 18:27
  • Also, the config database, where the transactions are stored. Feb 25, 2020 at 19:38
124

Try this command:

mongo --quiet --eval 'db.getMongo().getDBNames().forEach(function(i){db.getSiblingDB(i).dropDatabase()})'
5
  • 1
    Works great, and you don't have to create a js file for it. Nice.
    – Erik Honn
    Nov 25, 2013 at 13:50
  • What is the symetric to load it ?
    – nha
    Sep 13, 2014 at 19:14
  • One issue with this approach that I just found is that the db var persists through mongo console sessions so if someone was interacting with one of the databases then it would be excluded by the db.getSiblingDB call. Apr 21, 2016 at 18:30
  • 5
    Nice. This is perfect for Docker :D docker exec mongodb sh -c "mongo --quiet --eval 'db.getMongo().getDBNames().forEach(function(i){db.getSiblingDB(i).dropDatabase()})'"
    – perezmlal
    May 29, 2019 at 9:12
  • I went through the same issue and I found out this is the best solution for automation tasks. You aren't eager to write new files and download in a CI/CD pipeline so a one-liner script is very simple to manage Jan 14, 2020 at 14:10
28

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();
 })
1
  • Instead of writing if condition for every DB, we can simple put in an array and do a indexOf. Jan 7, 2019 at 5:25
16
db
  .getMongo()
  .getDBNames()
  .filter(n => !['admin','local','config'].includes(n))
  .forEach(dname =>
    db
      .getMongo()
      .getDB(dname)
      .dropDatabase()
  )
;

One-liner

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.

8

Save this to drop_all_dbs.js:

var databases = db.getMongo().getDBNames()
for(var i in databases){
    db = db.getMongo().getDB( databases[i] );
    if(db.getName() == "admin" || db.getName() == "local"){
        print("skipping db " + db.getName())
        continue
    }
    print( "dropping db " + db.getName() );
    db.dropDatabase();
}

Now you can execute:

mongo drop_all_dbs.js

and all databases (except for admin and local) will be dropped.

This answer is a copy of ALoR's one, just fix drop of system dbs

7

Adding to @ALoR's answer, for convenience you can put the following in ~/.mongorc.js

function dropDatabases(){
    var mongo = db.getMongo();

    var dbNames = mongo.getDBNames();
    for (var i = 0; i < dbNames.length; i++) {
        var db = mongo.getDB( dbNames[i] );

        print( "Dropping database " + db.getName() + "..." );
        db.dropDatabase();
    }
}

Then at the mongo shell you can simply do

dropDatabases()

From the docs:

Mongo will read the .mongorc.js file from the home directory of the user invoking mongo. In the file, users can define variables, customize the mongo shell prompt, or update information that they would like updated every time they launch a shell.

0
4

You can do it easy through c# official driver:

var _mongoServer = MongoServer.Create("mongodb://localhost:27020");

var names = _mongoServer.GetDatabaseNames();
foreach (var name in names)
{
   _mongoServer.DropDatabase(name);
}
3
  • yes it could be an idea, but I want to do it without C#. (Oh sorry, I used tag C# for this question)
    – John
    Jun 16, 2011 at 18:21
  • you can create a javascript loop that do the job and then execute it in the mongoconsole.
    – ALoR
    Jun 16, 2011 at 20:07
  • 2
    @AndrewOrsich and @JohnSmith i've posted the script.
    – ALoR
    Jun 17, 2011 at 11:42
1

Here is a oneliner that allows you to filter for specific names:

for (const dbName of db.getMongo().getDBNames().filter(dbName => dbName.startsWith('test-'))) {console.log(dbName); const dbToDelete = db.getMongo().getDB( dbName ); dbToDelete.dropDatabase()}
0

This is what worked best for me.

Save this to a file called drop_most_databases.js:

const databasesToSkip = ['admin', 'local', 'config'];
db.getMongo()
  .getDBNames()
  .forEach((dbname) => {
    if (databasesToSkip.includes(dbname)) {
      print(`Skipping ${dbname}`);
    } else {
      print(`Dropping ${dbname}...`);
      db.getMongo().getDB(dbname).dropDatabase();
    }
  });
print(`Now, the only databases that remain are:`);
db.getMongo()
  .getDBNames()
  .forEach((dbname) => {
    print(dbname);
  });

From Terminal, run mongo drop_most_databases.js.

-3

It is as easy as

mongo --eval 'db.dropDatabase()'

Or, you can start a mongo session on your terminal and write

db.dropDatabase()

Which is exactly the same.

1
  • The question is how to drop all databases, not an individual one
    – Rob H
    Jul 24, 2018 at 19:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.