【问题标题】:How to drop all databases in MongoDB?如何删除 MongoDB 中的所有数据库?
【发布时间】:2018-07-25 14:16:39
【问题描述】:

我的 MongoDB 中有一个数据库列表。如何删除除localadminconfig之外的所有数据库?

【问题讨论】:

  • 有趣。似乎没有以代码友好的方式枚举数据库(或其名称)的方法。有一个用于集合,但不是数据库。
  • 如果你知道名字,那很简单:db.getSiblingDB('Marks').dropDatabase()。所以你可以简单地硬编码这些名字。
  • @SergioTulentsev 实际上有一种方法可以做到这一点,只是没有正式记录。请在下面查看我的答案。

标签: database mongodb nosql


【解决方案1】:

您可以在mongo shell 中使用getDBNames() 方法。

必须从Mongo() instance 调用此方法。不幸的是,我认为getDBNames() 方法没有记录在案。

获取数据库名称后,您可以循环访问它们以删除不需要的名称,例如:

Mongo().getDBNames().forEach(function(x) {
  // loop through all the database names
  if (['admin', 'config', 'local'].indexOf(x) < 0) {
    // drop database if it's not admin, config, or local
    Mongo().getDB(x).dropDatabase();
  }
})

例如:

> show dbs
admin   0.000GB
config  0.000GB
local   0.001GB
test    0.000GB
test2   0.000GB
test3   0.000GB

> Mongo().getDBNames().forEach(function(x) {
...   if (['admin', 'config', 'local'].indexOf(x) < 0) {
...     Mongo().getDB(x).dropDatabase();
...   }
... })

> show dbs
admin   0.000GB
config  0.000GB
local   0.001GB

【讨论】:

    【解决方案2】:

    我使用 tutorial 修复了这个解决方案

    我在我的 mongo shell 中运行了这段代码

    var dbs = db.getMongo().getDBNames()
    for(var i in dbs){
        db = db.getMongo().getDB( dbs[i] );
        if (db.getName() !== 'admin' && db.getName() !== 'local') 
        {
            print( "dropping db " + db.getName() );  
            db.dropDatabase();
        }
    }
    

    【讨论】:

    • 谢谢。这很有用
    猜你喜欢
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2017-06-30
    • 2019-02-24
    • 2011-03-20
    • 1970-01-01
    相关资源
    最近更新 更多