How to truncate multiple MongoDB collections in a Database

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. 

  • http://emptysquare.net/ A. Jesse Jiryu Davis

    This script won’t retain indexes; collection.drop() removes all collection indexes. This script does have the advantage, however, over db.dropDatabase() of retaining all of MongoDB’s preallocated files for the database.

    • Manoj Vivek

      Yes, Jesse. I agree.
      The best way to truncate(retain indexes and delete the data) is to use db.collection.remove()