MongoDB has a drop() command that you can use to delete everything in a certain collection, but this also, unfortunately, will drop your indexes and other things too. What I wanted was a way that I could “truncate” the collection (borrowing from MySQL) and retain the indexes etc too.
The following snippet will do that, plus it has a built in “Oops, I changed my mind” safety check in case you need to cancel the collection truncate command.
var dbName = 'myDB'; db.getSiblingDB(dbName).getCollectionNames().forEach(function(collName) { // Drop all collections except system ones (indexes/profile) if (!collName.startsWith("system.")) { // Safety net print("WARNING: going to drop ["+dbName+"."+collName+"] in 5s .. hit Ctrl-C if you've changed your mind!"); sleep(5000); db[collName].drop(); } })
This would be best saved as a UDF in your mongo shell, and probably made to take a parameter for the db too…
Liked this post? Follow this blog to get more.