简体   繁体   中英

How to delete lots of mongodb collections at once?

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?

For regex you can use string.match

db.getCollectionNames().forEach(function(c) {
    if(!c.match("^system.indexes")) { 
        db.getCollection(c).drop();
    }
  });
# 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.getCollection(collection).drop();
        print("Deleted Collection: "+ collection);
    }
  })

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();
    }
  });

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM