Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropping MongoDB collections using regex

Tags:

mongodb

is it possible? I have auto-generated mongoDB collections that at a certain moment I need to drop. I know their collection name patterns and they are too many, so dropping them by hand is not an option. All examples I had a look at using regex were involving queries but not with database commands. I know I could iterate over all collections and filtering by their name I could get it working but I am looking for a more handy and single command (I want to use it directly in the shell), if possible :)

Any suggestions?

Thank you!

like image 454
jarandaf Avatar asked May 13 '13 10:05

jarandaf


2 Answers

You can do it using MongoDB console:

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

You can use any regexp to match your collections names.

like image 153
Leonid Beschastny Avatar answered Dec 03 '22 15:12

Leonid Beschastny


db.getCollectionNames().forEach(function(c) {
    if(c.match("^system.indexes")) { 
        db.getCollection(c).drop();
    }
  });
like image 42
mmmdreg Avatar answered Dec 03 '22 13:12

mmmdreg