MongoDB drop every database

后端 未结 8 1008
清歌不尽
清歌不尽 2021-01-29 19:30

I would like to know if there\'re a command to drop every databases from my MongoDB?

I know if I want to drop only one datatable, I just need to type the name of the dat

相关标签:
8条回答
  • 2021-01-29 19:45

    Save this to drop_all_dbs.js:

    var databases = db.getMongo().getDBNames()
    for(var i in databases){
        db = db.getMongo().getDB( databases[i] );
        if(db.getName() == "admin" || db.getName() == "local"){
            print("skipping db " + db.getName())
            continue
        }
        print( "dropping db " + db.getName() );
        db.dropDatabase();
    }
    

    Now you can execute:

    mongo drop_all_dbs.js
    

    and all databases (except for admin and local) will be dropped.

    This answer is a copy of ALoR's one, just fix drop of system dbs

    0 讨论(0)
  • 2021-01-29 19:45

    You can do it easy through c# official driver:

    var _mongoServer = MongoServer.Create("mongodb://localhost:27020");
    
    var names = _mongoServer.GetDatabaseNames();
    foreach (var name in names)
    {
       _mongoServer.DropDatabase(name);
    }
    
    0 讨论(0)
  • 2021-01-29 19:45

    It is as easy as

    mongo --eval 'db.dropDatabase()'
    

    Or, you can start a mongo session on your terminal and write

    db.dropDatabase()
    

    Which is exactly the same.

    0 讨论(0)
  • 2021-01-29 19:46

    Adding to @ALoR's answer, for convenience you can put the following in ~/.mongorc.js

    function dropDatabases(){
        var mongo = db.getMongo();
    
        var dbNames = mongo.getDBNames();
        for (var i = 0; i < dbNames.length; i++) {
            var db = mongo.getDB( dbNames[i] );
    
            print( "Dropping database " + db.getName() + "..." );
            db.dropDatabase();
        }
    }
    

    Then at the mongo shell you can simply do

    dropDatabases()
    

    From the docs:

    Mongo will read the .mongorc.js file from the home directory of the user invoking mongo. In the file, users can define variables, customize the mongo shell prompt, or update information that they would like updated every time they launch a shell.

    0 讨论(0)
  • 2021-01-29 19:48

    var mongo = db.getMongo(); mongo.getDBNames().filter(n => n != 'admin' && n != 'local' && n != 'config').forEach(function (dbname) { var db = mongo.getDB(dbname); db.dropDatabase(); });

    This one is safe to copy and execute on mongoshell. Credits to all answers above. Just exclude 'config' database as well.

    0 讨论(0)
  • 2021-01-29 19:52

    Try this command:

    mongo --quiet --eval 'db.getMongo().getDBNames().forEach(function(i){db.getSiblingDB(i).dropDatabase()})'
    
    0 讨论(0)
提交回复
热议问题