In MongoDB, users can have privileges across different databases.
In the following article i will show how to create, show and delete a user in MongoDB.
I will also show how to create a user with admin
and a user with root
(superuser) privileges on the all databases in MongoDB.
Create a User in MongoDB
Authentication Database: In MongoDB, user can have privileges across different databases. When adding a user, you create the user in a specific database. This database is the authentication database for this user.
Connect to MongoDB using mongo
shell:
$ mongo
Cool Tip: How to connect to remote MongoDB server from the command line using mongo
shell! Read More →
Create Admin/Root User in MongoDB
Switch to admin
database:
> use admin
Admin vs Root: The role userAdminAnyDatabase in MongoDB gives ability to create users and assign roles to them, but by itself it doesn’t allow the user to do anything else. The superuser role in MongoDB is the root.
Create mongo-admin
user:
> db.createUser( { user: "mongo-admin", pwd: "passw0rd", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )
Create mongo-root
user:
> db.createUser( { user: "mongo-root", pwd: "passw0rd", roles: [ { role: "root", db: "admin" } ] } )
Create User For Database
Switch to the database in which you would like to create a common user:
> use my-database
Create my-user
with readWrite permissions on my-database
:
> db.createUser( { user: "my-user", pwd: "passw0rd", roles: [ { role: "readWrite", db: "my-database" } ] } )
You can also create a user with different permissions on different databases.
For example, you can create my-user
and grant him readWrite permissions on my-database
and read permissions on another-database
:
> db.createUser( { user: "my-user", pwd: "passw0rd", roles: [ { role: "readWrite", db: "my-database" }, { role: "read", db:"another-database" } ] } )
Read more about built-in roles in the official documentation.
Cool Tip: Enable auth
in MongoDB (disabled by default)! Read More →
Show Users in MongoDB
Show users in the current database:
> db.getUsers() - or - > show users
Delete User in MongoDB
Delete a user from the current database:
> db.dropUser("my-user")
Perfection.
Damn Good. To the point. Thanks. Made me day in mins.