Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save activated/ded69f8f1ea9cd3ecee496a1c63313de to your computer and use it in GitHub Desktop.
Save activated/ded69f8f1ea9cd3ecee496a1c63313de to your computer and use it in GitHub Desktop.
Create root user on MongoDB
// 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