22

我的数据库中有很多 mongodb 集合需要删除。它们都有相似的名称,如果只使用通配符,则很容易删除它们。但看起来他们做不到。

有没有办法一次选择一堆集合来删除它们?

4

5 回答 5

29

对于正则表达式,您可以使用 string.match

db.getCollectionNames().forEach(function(c) {
    if(!c.match("^system.indexes")) { 
        db.getCollection(c).drop();
    }
  });
于 2013-02-11T12:10:38.100 回答
15
# 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);
    }
  })
于 2016-02-24T07:00:15.017 回答
8

您可以使用以下命令删除所有集合。

> use database_name;

> db.getCollectionNames().forEach(function(c) {
    if(c != 'system.indexes') { 
        db.getCollection(c).drop();
    }
  });
于 2012-06-26T12:25:02.627 回答
7

不,没有办法通过通配符/正则表达式删除多个集合。您必须将它们一一丢弃。我最近执行了一项类似的任务,我的脚本每秒能够丢弃约 20-30 个集合。你有多少?

于 2012-06-26T12:09:04.207 回答
4

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.

于 2013-09-23T16:18:23.103 回答