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