Forked from ramonfritsch/gist:2cb12f6b94e145451b6e
Last active
April 14, 2025 14:32
-
-
Save activated/ded69f8f1ea9cd3ecee496a1c63313de to your computer and use it in GitHub Desktop.
Create root user on MongoDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// to drop all databases | |
mongo --quiet --eval 'db.getMongo().getDBNames().forEach(function(i){db.getSiblingDB(i).dropDatabase()})' | |
use admin; | |
db.createUser( | |
{ | |
user: "user", | |
pwd: "pass", | |
roles: [ "root" ] | |
} | |
); | |
use database; | |
db.createUser( | |
{ | |
user: "user", | |
pwd: "pass", | |
roles: [ { role: "readWrite", db: "database" } ] | |
} | |
); | |
//-------------------------------------------------- | |
db | |
.getMongo() | |
.getDBNames() | |
.filter(n => !['admin','local','config'].includes(n)) | |
.forEach(dname => | |
db | |
.getMongo() | |
.getDB(dname) | |
.dropDatabase() | |
) | |
; | |
One-liner: | |
db.getMongo().getDBNames().filter(n => !['admin','local','config'].includes(n)).forEach(dname => db.getMongo().getDB(dname).dropDatabase()); | |
This drops all DBs but preserves MongoDB's internal collections. | |
//------ | |
Save this to drop_all_dbs.js: | |
var databases = db.getMongo().getDBNames() | |
for(var i in databases){ | |
db = db.getMongo().getDB( databases[i] ); | |
if(db.getName() == "admin" || db.getName() == "local"){ | |
print("skipping db " + db.getName()) | |
continue | |
} | |
print( "dropping db " + db.getName() ); | |
db.dropDatabase(); | |
} | |
Now you can execute: | |
mongo drop_all_dbs.js | |
//--------------------------------------------------------------- | |
docker exec mongodb sh -c "mongo --quiet --eval 'db.getMongo().getDBNames().forEach(function(i){db.getSiblingDB(i).dropDatabase()})'" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment