Delete everything in a MongoDB database
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.
Solution 1:
In the mongo shell:
use [database];
db.dropDatabase();
And to remove the users:
db.dropAllUsers();
Solution 2:
Also, from the command line:
mongo DATABASE_NAME --eval "db.dropDatabase();"
Solution 3:
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.".