Delete MongoDB database from Bash script

Viewed 121

I'm not a Bash/Linux person, but I've been asked to just come up with the lines needed to run to authenticate against a database and then drop it. Here is what I have so far and I'm not sure if it's correct:

mongo mydatabase –port –username <username> –password <password> –authenticationDatabase admin –eval “ printjson(db.dropDatabase())”

If it's possible to use one line to delete any database whose name starts with "cpt_" then that would be absolutely ideal.

Thanks!

1 Answers

You can use -

  • Get all the names
  • Loop and check if the name starts with cpt_
  • drop the database

db.getMongo().getDBNames().forEach(function(dbName){ if (dbName.startsWith('cpt_')) printjson(db.getSiblingDB(dbName).dropDatabase())

Full

mongo –port –username <username> –password <password> –authenticationDatabase admin --eval "db.getMongo().getDBNames().forEach(function(dbName){ if (dbName.startsWith('cpt_')) printjson(db.getSiblingDB(dbName).dropDatabase())  })"
Related