Thiyagu
Thiyagu

Reputation: 786

Need to delete mongodb collection with prefix based name

I have number of collection in my mongodb.

The collections names are like aaa_123,aaa_345,aaa_ccc,mmm,nnn and etc...

Many collections name has prefixed with aaa_ and also other collection name also present, I need to delete only the collection names prefixed with aaa_ , but in manual I deleted like db.aaa_123.drop(), its take long time to delete collection , Is there anyway to delete all collections with prefixed aaa_ in mongodb?

Anyhelp appreciated..

Upvotes: 1

Views: 1978

Answers (1)

charan tej
charan tej

Reputation: 1054

First Get all collection in DB to one variable then loop through that variable and check for that name in collection. If that check condition satisfies delete that collection. Check below for code sample

var collectionNames = db.getCollectionNames();
for(var i = 0, len = collectionNames.length; i < len ; i++){
    var collectionName = collectionNames[i];
    if(collectionName.indexOf('aaa_') == 0){
        db[collectionName].drop()
    }
}

Hope this helps

Upvotes: 3

Related Questions