How to delete lots of mongodb collections at once?

前端 未结 5 510
刺人心
刺人心 2020-12-09 04:06

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 cou

相关标签:
5条回答
  • 2020-12-09 04:40

    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();
        }
      });
    
    0 讨论(0)
  • 2020-12-09 04:43

    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?

    0 讨论(0)
  • 2020-12-09 04:45

    For regex you can use string.match

    db.getCollectionNames().forEach(function(c) {
        if(!c.match("^system.indexes")) { 
            db.getCollection(c).drop();
        }
      });
    
    0 讨论(0)
  • 2020-12-09 04:48

    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.

    0 讨论(0)
  • 2020-12-09 04:58
    # 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);
        }
      })
    
    0 讨论(0)
提交回复
热议问题