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:
1 |
./mongod --dbpath=/Users/Khanh/MongoDB/data/db |
Then, use mongo file of MongoDB to log in to this server as follows:
1 |
./mongo |
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:
Then, we will use MongoDB ‘s createUser() method to add to this database a user like this:
1 2 3 4 5 6 |
db.createUser({ user: "<username>", pwd: "<password>", roles: [{ role: "<role1>", db: "<db1>" }, { role: "<role2>", db: "<db2>" },...] }) |
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:
1 2 3 4 5 |
db.createUser({ user: "khanh", pwd: "abc123", roles: [{ role: "root", db: "admin" }] }) |
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:
OK, now we can use this new user to log into MongoDB server.
I will restart MongoDB with the parameter “–auth” as follows:
1 |
./mongod --auth --dbpath=/Users/Khanh/MongoDB/data/db |
Now, if I do not log in to MongoDB with a user and manipulate on the admin database, then the following error will appear:
Now I will log into the MongoDB server with the user that I have created above with the following structured statement:
1 |
./mongo -u <username> -p <password> --authenticationDatabase <database> |
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:
1 |
./mongo -u "khanh" -p "abc123" --authenticationDatabase "admin" |
Then, I can manipulate the admin database without any problems: