Skip to content
Advertisement

In “mongosh”, how do I delete all databases without deleting the typical “admin”, “config”, or “local” databases?

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

JavaScript

Inside mongosh:

JavaScript

Before what I did to successfully delete these databases was:

JavaScript

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

JavaScript

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.

Advertisement

Answer

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

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement