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()?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With