Home > Net >  In "mongosh", how do I delete all databases without deleting the typical "admin"
In "mongosh", how do I delete all databases without deleting the typical "admin"

Time:09-21

What am I trying to do?

I wrote a script called deleteDatabases.js and it's supposed to delete all databases (besides "admin", "config", or "local") when inside mongosh. I do not have access to mongo, only mongosh.

What is the code that currently tries to do that?

deleteDatabases.js

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

Inside mongosh:

$ mongosh
...
Using MongoDB: 4.4.1
Using Mongosh Beta: 0.4.0
> show dbs
admin 184 kB
config 36.9 kB
database1 283 kB
database2 420 kB
database3 1337 kB
local 90.1 kB
> .load /deleteDatabases.js

... (Code from deleteDatabases.js) ...

TypeError: (intermediate value).getDBNames is not a function

Before what I did to successfully delete these databases was:

> db = db.getSiblingDB("database1")
database1
> db.dropDatabase()
{ ok: 1, dropped: 'database1' }
# Repeat for each database I want deleted.

What do I expect the result to be?

I expect all the databases to be deleted besides "admin", "config", or "local".

What is the actual result?

As above, there's a TypeError.

What I think the problem could be?

  1. The version of mongosh I'm using is out of date and does not have those methods implemented yet or at all.
  2. My .js file is implemented incorrectly.

Was wondering if there was an alternative where I still use mongosh unless I have to use something else.

EDIT:

deleteDatabases.js

db.adminCommand( { listDatabases: 1 } ).databases.
  map(database => database.name).
  filter(name => ["admin", "config", "local"].indexOf(name) == -1).
  forEach(function(name){db.getSiblingDB(name).dropDatabase()})

This is the fix that I'm using, but would love the .map() to work so I can see an output after running the command as spoken by Joe.

CodePudding user response:

Use the listDatabases admin command, map to get just the database name, and filter to eliminate the ones you don't want:

db.adminCommand("listDatabases").databases.
   map(d => d.name).
   filter(n => ["admin", "config", "local"].indexOf(n) == -1 ).
   map(n => db.getSiblingDB(n).dropDatabase())

Note that if you use map instead of forEach you will get back a confirmation of which databases were dropped successfully, like

[
  { ok: 1, dropped: 'test' },
  { ok: 1, dropped: 'test1' },
  { ok: 1, dropped: 'test2' }
]
  • Related