Removing MongoDB Collections Using Regular Expression

Is it possible? I have mongoDB auto-generated collections that I need to drop at some point. I know their collection name templates, and there are too many of them, so dropping them manually is not an option. All the examples I used when using regular expressions included queries, but not with database commands. I know that I can iterate over all collections and filter them by name, I could make it work, but I am looking for a more convenient and single command (I want to use it directly in the shell), if possible :)

Any suggestions?

Thanks!

+6
source share
2 answers

You can do this using the MongoDB console:

regExp = /test/; db.getCollectionNames().filter(function(name){ return name.match(regExp) }).forEach(function(name){ db.getCollection(name).drop() }); 

You can use any regular expression to match your collection names.

+12
source
 db.getCollectionNames().forEach(function(c) { if(c.match("^system.indexes")) { db.getCollection(c).drop(); } }); 
+4
source

Source: https://habr.com/ru/post/944868/


All Articles