Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop Collections in MongoDB Database

Tags:

mongodb

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()?

like image 808
Woodchuck Avatar asked Jul 15 '26 03:07

Woodchuck


1 Answers

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).

like image 62
brezniczky Avatar answered Jul 17 '26 23:07

brezniczky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!