Removing all collections whose name matches a string in MongoDB

To remove all collections whose name matches a string in MongoDB, use a for loop to iterate over all collections, check for the string pattern using indexOf(), and apply the drop() method to matching collections.

Syntax

var allCollectionNames = db.getCollectionNames();
for(var i = 0; i < allCollectionNames.length; i++){
    var colName = allCollectionNames[i];
    if(colName.indexOf('searchString') == 0){
        db[colName].drop();
    }
}

Sample Data

Let's say we are using the database "sample" with the following collections ?

show collections;
arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteMultipleIdsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
getAllRecordsFromSourceCollectionDemo
insertDocumentWithDateDemo
sourceCollection
studentInformation
updateInformation
userInformation

Example: Remove Collections Starting with "delete"

Now remove all collection names that start with the string "delete" ?

var allCollectionNames = db.getCollectionNames();
for(var j = 0, colLength = allCollectionNames.length; j < colLength; j++){
    var colName = allCollectionNames[j];
    if(colName.indexOf('delete') == 0){
        db[colName].drop();
    }
}
true

Verify Result

Check the remaining collections to confirm deletion ?

show collections;
arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
getAllRecordsFromSourceCollectionDemo
insertDocumentWithDateDemo
sourceCollection
studentInformation
updateInformation
userInformation

Key Points

  • indexOf('string') == 0 checks if the collection name starts with the specified string.
  • Use indexOf('string') !== -1 to match collections containing the string anywhere in the name.
  • The drop() method permanently deletes collections ? use with caution.

Conclusion

Use getCollectionNames() with a for loop and indexOf() to identify collections matching a pattern, then apply drop() to remove them. This approach provides flexible pattern matching for bulk collection removal.

Updated on: 2026-03-15T00:35:49+05:30

579 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements