How to delete lots of mongodb collections at once?

2019-01-17 22:54发布

问题:

There are a lot of mongodb collections in my database that I need to delete. They all have similar names, and it would be easy to delete them if only wildcard characters could be used. But it doesn't look like they can.

Is there a way to select a bunch of collections at once to delete them?

回答1:

For regex you can use string.match

db.getCollectionNames().forEach(function(c) {
    if(!c.match("^system.indexes")) { 
        db.getCollection(c).drop();
    }
  });


回答2:

No, there's not a way to drop several collections by a wildcard/regex. You have to drop them one by one. I recently performed a similar task and my script was able to drop ~20-30 collections per second. How many do you have?



回答3:

# Delete Particular Collections From MongoDB

> use database_name

> delete_collection_list = ["collection1", "collection2", "collection3", "collection4", "collection5", "collection6"]

> delete_collection_list.forEach( function (collection) {
    if (db.getCollectionNames().indexOf(collection)>=0) {
        db[collection].drop();
        print("Deleted Collection: "+ collection);
    }
  })


回答4:

You can delete all the collections using the following command.

> use database_name;

> db.getCollectionNames().forEach(function(c) {
    if(c != 'system.indexes') { 
        db.getCollection(c).drop();
    }
  });


回答5:

You can drop every collection in the database with db.dropDatabase() in the mongo shell. Just make sure you really want to nuke everything before you do.