Removing all collections whose name matches a string in MongoDB


To remove all collections whose name matches a string, you can follow some steps. Use for loop to iterate over all collections and find that particular collection name with certain string. After that, use the drop method to remove all collections.

Let’s say we are using the database “sample”. The collections are as follows in sample database

> show collections;

This will produce the following output

arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteMultipleIdsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findMimimumElementInArrayDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
insertDocumentWithDateDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
sumTwoFieldsDemo
truncateDemo
updateInformation
userInformation

Now remove all the collection names that match a string “delete”. Following is the query

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

This will produce the following output

True

Now you can see there are no collections with name “delete” because all collections have been removed successfully from the sample database.

Now let us check all the collection names. Following is the query

> show collections;

This will produce the following output

arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findMimimumElementInArrayDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
insertDocumentWithDateDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
sumTwoFieldsDemo
truncateDemo
updateInformation
userInformation

Updated on: 30-Jul-2019

403 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements