Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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') == 0checks if the collection name starts with the specified string. - Use
indexOf('string') !== -1to 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.
Advertisements
