Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Removing all collections whose name matches a string

Tags:

mongodb

I've restructured my database a bit, and no longer have need for certain collections. However, there are far too many of them to remove by-hand (thousands, actually). Each of the collections in question begins with "cache_" and contains a couple of indexes which I'd like to make sure are completely cleaned up.

I'm trying to understand how to use the mongo shell in order to loop over all collection names and remove those collections which begin with "cache_". Per the Queries & Cursors documentation, I understand how to loop over documents within a collection, but not how to use the MongoDB shell to loop through the collections in the database.

In pseudo-code, this is what I need:

var all_collections = show collections
for(var collection in all_collections)
    if(collection.name.indexOf('cache_')==0)
        collection.drop()

FWIW, I've done searching for "mongodb loop through collection names" etc. and have not found anything, but maybe I sux at teh googlez =P

On a related note... after doing this degree of restructuring, should I be doing a db.repairDatabase() or anything of the sort in order to make sure the dropped indexes etc. are all nice and clean?

Thanks.

like image 749
Zane Claes Avatar asked Oct 11 '12 16:10

Zane Claes


People also ask

How do I delete multiple collections in MongoDB?

In MongoDB, you are allowed to delete the existing documents from the collection using db. collection. deleteMany() method. This method deletes multiple documents from the collection according to the filter.

What is the fastest operation to clear an entire collection in MongoDB?

drop() will delete to whole collection (very fast) and all indexes on the collection.

Does removing all collections in a database also remove the database?

Yes, to all.


2 Answers

Use db.getCollectionNames() to get the all the collections and store them in an array.

var collectionNames = db.getCollectionNames();
for(var i = 0, len = collectionNames.length; i < len ; i++){
    var collectionName = collectionNames[i];
    if(collectionName.indexOf('cache_') == 0){
        db[collectionName].drop()
    }
}
like image 64
driangle Avatar answered Oct 18 '22 20:10

driangle


Just to add another answer found on mongodb mailing list

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

You probably want to not drop the local/config/admin dbs as I've listed above.

like image 29
Nishant Avatar answered Oct 18 '22 19:10

Nishant