Home > Software engineering >  How to delete MongoDB databases that match specific condition?
How to delete MongoDB databases that match specific condition?

Time:10-21

I have many databases, I can delete them one by one. But there are too many databases, How can I delete them at once.

For example, delete all databases that name has recommend.

CodePudding user response:

The listDatabases command returns all of the databases, you could iterate that list to drop the ones matching the criteria.

In the mongo shell that might look like:

db.adminCommand("listDatabases").databases.
    filter(d => d.name.match(/recommend/)).
    map(d => db.getSiblingDB(d.name).dropDatabase())

CodePudding user response:

You can use the db.adminCommand

db.adminCommand("listDatabases").databases.forEach( function (d) {
    if (d.name == "recommend")
        db.getSiblingDB(d.name).dropDatabase();
 })

With this, you can add multiple conditionals for specific db.

Here list of avaliable commands: https://docs.mongodb.com/manual/reference/command/nav-administration/

Here more documentation about it: https://docs.mongodb.com/manual/reference/method/db.adminCommand/

  • Related