Richard Wolford
Richard Wolford

Reputation: 453

Delete MongoDB database from Bash script

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!

Upvotes: 2

Views: 474

Answers (1)

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())  })"

Upvotes: 3

Related Questions