Setting up authentication in MongoDB and creating a superuser account
In this recipe, we will look at how to create a superuser account in MongoDB and force MongoDB to use authentication.
Getting ready
You need a standard MongoDB installation.
How to do it...
- Assuming you already have mongod running, connect to the mongod instance using the mongo shell and switch to the
admin
database:
use admin
- Create a superuser account:
db.createUser( { user: "superadmin", pwd: "supasecret", roles: [{role: "root", db: "admin"}] } )
- You should see an output similar to this:
Successfully added user: { "user" : "superadmin", "roles" : [ { "role" : "root", "db" : "admin" } ] }
- Restart the mongod instance with
auth
enabled:
mongod --dbpath /data/db --auth
- Connect to the mongod instance and attempt any regular operation:
show dbs
- You should see an output similar to this:
2017-10-12T11:21:09.966+0000 E QUERY...