Create and grant access to MongoDB user

By default, you can start to use MongoDB server without having to log in with any user as I did in the tutorial how to install MongoDB on macOS. But in some cases, like the production environment, it’s much better to work with the MongoDB server using a user. In this case, you need to start MongoDB server with “–auth” parameter and use the user to log into MongoDB server. In this tutorial, I will guide you all how to create new and grant access to MongoDB user to use.

First, please start MongoDB server, as usual, myself as follows:

Then, use mongo file of MongoDB to log in to this server as follows:

To create a new MongoDB user, we need to select the database that this user will use. Here, I choose the MongoDB database admin as follows:

Create and grant access to MongoDB user

Then, we will use MongoDB ‘s createUser() method to add to this database a user like this:

Inside:

  • <username> is the name of the user that you want to add.
  • <password> is the password of this user.
  • <role1>, <role2> is the user’s role declaration for the database to which it is assigned. We have the MongoDB default roles https://docs.mongodb.com/manual/reference/built-in-roles/ and the roles which we can create.
  • <db1>, <db2>: although we have declared using a database (in our example database “admin”), this user can also be used in other databases, specify in this command.

In this example, I will execute the createUser() method with the following contents:

As you can see, in the above statement, I added a user named “Khanh” and the password is “abc123”. This user can only be used with the admin database with the Superuser role “root” https://docs.mongodb.com/manual/reference/built-in-roles/#superuser-roles.

Result:

Create and grant access to MongoDB user

OK, now we can use this new user to log into MongoDB server.

I will restart MongoDB with the parameter “–auth” as follows:

Now, if I do not log in to MongoDB with a user and manipulate on the admin database, then the following error will appear:

Create and grant access to MongoDB user

Now I will log into the MongoDB server with the user that I have created above with the following structured statement:

Inside:

  • <username> is the login name
  • <password> is the password of the user
  • <database> is the name of the database that the user has been assigned.

Myself as follows:

Then, I can manipulate the admin database without any problems:

Create and grant access to MongoDB user

Add Comment