- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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