#TIL 9 - Delete all databases on mongo db on local | ProductsWay

#TIL 9 - Delete all databases on mongo db on local

Feb 4, 2021 · Dung Huynh

What

Drop every application database on your local MongoDB instance while preserving the admin, config, and local system databases.

Why

Switching between projects leaves test databases behind. Filter the protected system databases out of getDBNames(), then call dropDatabase() on each remaining sibling database. Run this only against a disposable local instance.

How

mongo --quiet --eval 'db.getMongo().getDBNames().filter(function(i){return ["admin","config","local"].indexOf(i) === -1}).forEach(function(i){db.getSiblingDB(i).dropDatabase()})'

For MongoDB 5+ (mongosh):

mongosh --quiet --eval 'db.getMongo().getDBNames().filter(i=>!["admin","config","local"].includes(i)).forEach(i=>db.getSiblingDB(i).dropDatabase())'