In short, the steps are as follows:
- connect mongo
mongo - Enter the admin database
use admin - Creating a user in the administrator account mongodb is based on the identity role, and the role of the administrator account is userAdminAnyDatabase. As the name implies, it is a super administrator. Later, you can access all the contents of the database through the command line similar to mysql connecting to the database. The operation is as follows: mongo -u root -p Then enter the password: adminPassword
db.createUser({ user: "adminName", pwd: "adminPassword", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] })
- Verify that the user is added successfully in step 3
db.auth("adminName", "adminPassword")
# If it returns 1, it means success.db.auth()
The method is understood as the user's authentication functionexit #
to exit the system - Modify the configuration to find the uncomment and modify it to:
sudo vim /etc/mongod.conf
#security:
security:
authorization: enabled #!!!注意首行空两个,缩进错误将会导致第6步重启失败
restart mongodb
sudo service mongod restart
- Enter mongodb, log in with the administrator account in step 3, and use this account to create other database administrator accounts
use admin
db.auth("adminName", "adminPassword")
Create a new account and password for the mongodb data you need to manage. # dbOwner represents the database owner role and has the highest authority of the database. such as creating an index
use yourDatabase
db.createUser({ user: "yourUser", pwd: "yourPassword", roles: [{ role: "dbOwner", db:"yourDatabase" }] })
- Create a new database read and write account # This user is used to read and write the data, and only has read and write permissions.
use yourdatabase
db.createUser({ user: "yourUser2", pwd: "yourPassword2", roles: [{ role: "readWrite",db: "yourDatabase" }] })
- The username and password for the data are now created.
Use: to linkmongodb://yourUser2:yourPassword2@localhost/yourDatabase