Woodchuck
Woodchuck

Reputation: 4474

Drop Collections in MongoDB Database

Is there a way to drop all the collections in a MongoDB database using one command, without needing to name each individual collection?

From what I've found, it looks like the command to do this is db.dropDatabase(). But that gives me an Unauthorized error:

> use MyDb
switched to db MyDb
> db.dropDatabase();
{
    "ok" : 0,
    "errmsg" : 
        "not authorized on MyDb to execute command 
            { dropDatabase: 1.0, $db: \"MyDb\" }",
    "code" : 13,
    "codeName" : "Unauthorized"
}

However, I can drop each collection in the db with no problem using db.collection.drop().

> use MyDb
switched to db MyDb
> db.collection1.drop();
true
> db.collection2.drop();
true
> db.collection3.drop();
true

So is there a way to drop all collections in a MongoDB database other than using db.dropDatabase()?

Upvotes: 7

Views: 6031

Answers (2)

h q
h q

Reputation: 1510

You may grant root role access to the (e.g. admin) user:

use admin;
db.grantRolesToUser("admin", ["root"]);
use MyDb;
db.dropDatabase();

To revoke access:

use admin;
db.revokeRolesFromUser("admin", ["root"]);

You may show the user roles by

show users;

Upvotes: 0

brezniczky
brezniczky

Reputation: 542

You can try the following:

db.getCollectionNames().forEach(function(x) {db[x].drop()})

It should work given your experiments about your privileges.

However, dropDatabase() should lead to a more appropriate solution, as mentioned in Delete everything in a MongoDB database, so looking at your user's role/privileges may be a preferable approach to take if the scenario recurs.

You'll also find an at the time writing more or less correct approach for avoiding the deletion of system collections there ("system." is sought in any part of the collection name).

Upvotes: 17

Related Questions