Delete everything in a MongoDB database

Mongodb

Mongodb Problem Overview


I'm doing development on MongoDB. For totally non-evil purposes, I sometimes want to blow away everything in a database—that is, to delete every single collection, and whatever else might be lying around, and start from scratch. Is there a single line of code that will let me do this? Bonus points for giving both a MongoDB console method and a MongoDB Ruby driver method.

Mongodb Solutions


Solution 1 - Mongodb

In the mongo shell:

use [database];
db.dropDatabase();

And to remove the users:

db.dropAllUsers();

Solution 2 - Mongodb

Also, from the command line:

mongo DATABASE_NAME --eval "db.dropDatabase();"

Solution 3 - Mongodb

I had the same problem, when I needed to reset all the collections but didn't want to loose any database users. Use the following line of code, if you would like to save the user configuration for the database:

use <whichever database>
db.getCollectionNames().forEach(function(c) { if (c.indexOf("system.") == -1) db[c].drop(); })

This code will go through all collection names from one database and drop those which do not start with "system.".

Solution 4 - Mongodb

I followed the db.dropDatabase() route for a long time, however if you're trying to use this for wiping the database in between test cases you may eventually find problems with index constraints not being honored after the database drop. As a result, you'll either need to mess about with ensureIndexes, or a simpler route would be avoiding the dropDatabase alltogether and just removing from each collection in a loop such as:

db.getCollectionNames().forEach(
  function(collection_name) {
    db[collection_name].remove()
  }
);

In my case I was running this from the command-line using:

mongo [database] --eval "db.getCollectionNames().forEach(function(n){db[n].remove()});"

Solution 5 - Mongodb

db.getCollectionNames().forEach(c=>db[c].drop())

Solution 6 - Mongodb

By compiling answers from @Robse and @DanH (kudos!), I've got the following solution which completely satisfies me:

db.getCollectionNames().forEach( function(collection_name) { 
  if (collection_name.indexOf("system.") == -1) 
       db[collection_name].drop();
  else  
       db[collection_name].remove({});
});

It cleans the database by dropping the user collections and emptying the system collections.

Solution 7 - Mongodb

Here are some useful delete operations for mongodb using mongo shell

To delete particular document in collections: db.mycollection.remove( {name:"stack"} )

To delete all documents in collections: db.mycollection.remove()

To delete any particular collection : db.mycollection.drop()

to delete database : first go to that database by use mydb command and then

db.dropDatabase()

Solution 8 - Mongodb

in case you'd need to drop everything at once: (drop all databases at once)

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

Solution 9 - Mongodb

Use

[databaseName]
db.Drop+databaseName();

drop collection 

use databaseName 
db.collectionName.drop();

Solution 10 - Mongodb

if you want to delete only a database and its sub-collections use this :

  • use <database name>;
  • db.dropDatabase();

if you want to delete all the databases in mongo then use this :

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

Solution 11 - Mongodb

I prefer

db.your_collection.remove({})

over

db.your_collection.drop()

If your collection was a special collection i.e a capped collection or a collection with one field marked as unique, dropping will clear the collection itself and when collection is again created it will be an ordinary collection. You will have to define the properties again. So use remove() to clear the documents without removing the collection and affecting the behavior of the collection.

Solution 12 - Mongodb

Simplest way to delete a database say blog:

> use blog
switched to db blog
> db.dropDatabase();
{ "dropped" : "blog", "ok" : 1 }

Solution 13 - Mongodb

For Meteor developers.

  1. Open a second terminal window while running your app in localhost:3000.

  2. In your project's folder run, meteor mongo.

    coolName = new Mongo.Collection('yourCollectionName');

  3. Then simply enter db.yourCollectionName.drop();

  4. You'll automatically see the changes in your local server.

For everybody else.

db.yourCollectionName.drop();

Solution 14 - Mongodb

  1. List out all available dbs show dbs
  2. Choose the necessary db use
  3. Drop the database db.dropDatabase() //Few additional commands
  4. List all collections available in a db show collections
  5. Remove a specification collection db.collection.drop()

Hope that helps

Solution 15 - Mongodb

To delete all DBs use:

for i in $(mongo --quiet --host $HOSTNAME --eval "db.getMongo().getDBNames()" | tr "," " ");

do mongo $i --host $HOSTNAME --eval "db.dropDatabase()";

done 

Solution 16 - Mongodb

use <dbname>
db.dropAllUsers()
db.dropAllRoles()
db.dropDatabase()

MongoDB db.dropDatabase() documentation explaining the modification introduced in 2.6:

> Changed in version 2.6: This command does not delete the users associated with the current database.

Solution 17 - Mongodb

In MongoDB 3.2 and newer, Mongo().getDBNames() in the mongo shell will output a list of database names in the server:

> Mongo().getDBNames()
[ "local", "test", "test2", "test3" ]

> show dbs
local  0.000GB
test   0.000GB
test2  0.000GB
test3  0.000GB

A forEach() loop over the array could then call dropDatabase() to drop all the listed databases. Optionally you can opt to skip some important databases that you don't want to drop. For example:

Mongo().getDBNames().forEach(function(x) {
  // Loop through all database names
  if (['admin', 'config', 'local'].indexOf(x) < 0) {
    // Drop if database is not admin, config, or local
    Mongo().getDB(x).dropDatabase();
  }
})

Example run:

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
test2   0.000GB
test3   0.000GB

> Mongo().getDBNames().forEach(function(x) {
...   if (['admin', 'config', 'local'].indexOf(x) < 0) {
...     Mongo().getDB(x).dropDatabase();
...   }
... })

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTrevor BurnhamView Question on Stackoverflow
Solution 1 - MongodbJosh KView Answer on Stackoverflow
Solution 2 - MongodbRimianView Answer on Stackoverflow
Solution 3 - MongodbGeringView Answer on Stackoverflow
Solution 4 - MongodbDanHView Answer on Stackoverflow
Solution 5 - MongodbSelvakumar PonnusamyView Answer on Stackoverflow
Solution 6 - MongodbBogdan DView Answer on Stackoverflow
Solution 7 - MongodbbhvView Answer on Stackoverflow
Solution 8 - MongodbsjasView Answer on Stackoverflow
Solution 9 - MongodbMohamed El GamalView Answer on Stackoverflow
Solution 10 - Mongodbuser2719890View Answer on Stackoverflow
Solution 11 - MongodbSreeragh A RView Answer on Stackoverflow
Solution 12 - MongodbShalabh RaizadaView Answer on Stackoverflow
Solution 13 - MongodbFelipe AlarconView Answer on Stackoverflow
Solution 14 - Mongodbpriya rajView Answer on Stackoverflow
Solution 15 - MongodbZaurView Answer on Stackoverflow
Solution 16 - MongodbAntonio BardazziView Answer on Stackoverflow
Solution 17 - MongodbkevinadiView Answer on Stackoverflow