Home MongoDB How to create User & add Role in MongoDB

How to create User & add Role in MongoDB

by Abraham
mongodb create use and role

MongoDB is a cross-platform document-oriented database that makes data storage and retrieval fast and easy. The database uses a JSON-like structure for the documents, primarily familiar to modern applications.

MongoDB uses collections and manuscripts whereby documents consist of key-value pairs, the basic unit of data in MongoDB. In contrast, collections contain functions and documents equivalent to relational database tables.

Create a new user in MongoDB

To add new users to the system, MongoDB provides an internal technique known as db.createUser(). In contrast to traditional Database systems, MongoDB users are bound to a local database called an Authentication Database. Thus, they are not globally tied, like conventional SQL databases.

Moreover, the authentication database and the user’s name serve as a unique identifier. Hence, if two users are created in different databases but share the same names, they are identified as two separate users. Therefore, if one wants to create a single user with permissions on multiple databases, one should allow a single user to have rights/roles to the applicable database instead of building the User numerous times in different databases.

Example:

db.createUser(

{       user: "Foss",

        pwd: "password",

         roles:[{role: "userAdminAnyDatabase" , db:"admin"}]})

User management commands

Name/sDescription
createUserThis method creates a new user.
dropAllUsersFromDatabaseDeletes all users from a database.
dropUserGrants a task and its privileges to a user.
grantRolesToUserA role and its associated privileges are assigned to a user.
revokeRolesFromUserRemoves a user's role.
updateUserThis method is used to update a user's data.
usersInfoThis method returns information about the users supplied.

Adding a user

When adding the user to a specified DB, use the “db.createUser()” method. It is important to note that adding users with options is much simpler than inserting a user document into a non-relational database.

Example:

use foss               // specify the DB

db.createUser(

  {

    user: "fosslinux",

    pwd: passwordPrompt(),  // or cleartext password if you wish

    roles: [

       { role: "read", db: "foss" },

       { role: "read", db: "articles" },

       { role: "read", db: "tutorials" },

       { role: "readWrite", db: "tutorialguides" }

    ]

  }

)

Once you have connected the MongoDB instance in the above example, you can attach it to the foss DB to execute the db.createUser() command. The database used will act as the User’s Authentication Database.

The password and username are supplied in the document that contains our method call as key-value pairs. The use of roles controls access to databases. A user must have a role to access any database, even its own Authentication Database. Also, a user is given access to other databases in the system using roles. Thus, a user’s privileges are not limited to their authentication database. Therefore, this enables users to have various privileges across the many databases as needed. The principle of the least privilege allows users to keep the database’s access scope as small as possible.‍

How to create an administrator user in MongoDB

Creating an admin user in MongoDB is done using the db.createUser() method, which allows you to create a user. However, after creating a user, you need to assign administrator roles. These roles give the user administrator privileges.

Create a user for a single database in MongoDB

If we want to create a user who can only work with one database, we can use a similar command as above, but we must use the “userAdmin” option just once.

Example:

db.createUser(

{        user: "Fosslinux",

         pwd: "password",

         roles:[{role: "userAdmin" , db:"Foss"}]})

Code breakdown:

  1. First and foremost, one should specify the “username” and “password” to be created.
  2. Assign the role for that User, which is the database administrator; this is assigned to the “user admin” role since the role allows the user to have administrative privileges only to the database specified in the DB
  3. Finally, the DB parameter sets the database on which the User should have administrative rights.

Managing users

To manage users, one needs to understand the roles that need to be defined since MongoDB has a whole list of functions like read-role and the read-write role. The “read role” command only allows read-only access to the databases. The “read-write role” provides read and write access to the database; this means that the user can issue the update, insert and delete commands on the collections in that database.

Example:

db.createUser(
{
            user: "Foss",

            pwd: "password",

            roles:[

            {
                        role: "read" , db:"Tutorials"},

    {
                        role: "readWrite" , db:"Guides"}

            }
                          ]
})

The above example shows that a user known as Foss is created and assigned several roles in multiple DBs. In the same model, Foss is given Read-Only permission on the “Tutorials” database and Read-Write permissions on the “Guides” database.

Adding roles to the MongoDB

Roles grant users access to MongoDB resources. Moreover, MongoDB provides several built-in roles that enable the administrators to control the access to a MongoDB system. However, when these roles cannot describe the desired set of privileges, one can create new roles in a particular database. Except for functions created in the admin database, a role can only include rights that apply to its database and those inherited from other roles.

A role defined in the admin database may contain rights applicable to the admin database, other databases, or the cluster resource, and may inherit roles from other databases. To establish a new role, use “db.createRole()” and specify the rights array and the inherited roles array.

MongoDB defines roles uniquely by combining the database name with the role name. Each role is scoped to the database you create, but MongoDB stores all role information in the adminSystemRoles collection in the admin database. For instance, the creative role and grant roles actions on the database resource must ensure that roles are created and granted in the database. The grantRole specifies the privileges for the new roles and the roles to inherit. The User AdminAnyDatabase and the Built-in roles user admin provide the CreateRole and grant roles actions on their respective resources.

To create a role with the authentication restrictions specified, one must set AuthenticationRetrictions action on the database resource, which the function is then created.

The db.grantRole to User () method takes the following arguments;

ParameterType Description
UserString Entails the name of the User to whom to grant the roles.
RolesArray Entails an array of additional roles to grant to the User.
Write concernDocument It is optional and aimed at modification of command. It also takes the same fields with the get last error command.

The roles parameter can specify both the user-defined and built-in functions, which can be achieved by selecting the role with its name. This is accomplished by connecting to the mongod (a primary daemon process for MongoDB system that handles data requests, performs background management operations, and manages data access). Alternatively, the mongos (which is responsible for establishing a connection between the client apps and the sharded cluster ), with the rights given in the requirements section. For instance, my user admin created in an enable access control can create roles in the admin and other databases.

Role management commands

Name\sDescription
createRoleCreates a role and says what it can do.
dropRoleRemoves the role that was set by the user.
dropAllRolesFromDatabaseRemoves all roles that users from a database set up.
grantPrivilegesToRoleassigns privileges to a role that the user chooses.
grantRolesToRoletells which roles a user-defined role can inherit privileges from.
invalidateUserCacheWhen you use invalidateUserCache, the in-memory cache of user information, such as credentials and roles, is flushed.
revokePrivilegesFromRoleremoves the privileges from a user-defined role that has them.
revokeRolesFromRoleremoves the inherited roles from a user-defined role that you don't want.
rolesInforeturns information about the role or roles you want.
updateRoleUpdates a role that was set up by the user.

Conclusion

The MongoDB database, which enables storage and retrieval of data to be easy and fast, can allow one to create a user using the “db.createUser()” command. On the other hand, the “AdminAnyDatabase” command provides users with all privileges to access the DB under the admin role. This article has gone the extra mile and illustrated how-to grant roles and rights. We hope you find it helpful. If yes, don’t forget to leave a remark in the comments section below.

You may also like

Leave a Comment

fl_logo_v3_footer

ENHANCE YOUR LINUX EXPERIENCE.



FOSS Linux is a leading resource for Linux enthusiasts and professionals alike. With a focus on providing the best Linux tutorials, open-source apps, news, and reviews written by team of expert authors. FOSS Linux is the go-to source for all things Linux.

Whether you’re a beginner or an experienced user, FOSS Linux has something for everyone.

Follow Us

Subscribe

©2016-2023 FOSS LINUX

A PART OF VIBRANT LEAF MEDIA COMPANY.

ALL RIGHTS RESERVED.

“Linux” is the registered trademark by Linus Torvalds in the U.S. and other countries.