How to set a password for mongodb

In short, the steps are as follows:

      1. connect mongo         
        mongo
      2. Enter the admin database   
        use admin  
      3. 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" }] })

      4. 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 function
        exit   # to exit the system
      5. Modify the configuration to find  the uncomment and modify it to:
        sudo vim /etc/mongod.conf
        #security:
        security:
        authorization: enabled #!!!注意首行空两个,缩进错误将会导致第6步重启失败
      6. restart mongodb
        sudo service mongod restart
      7. 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")
      8. 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" }] })
      9. 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" }] })
      10. The username and password for the data are now created.
        Use: to linkmongodb://yourUser2:yourPassword2@localhost/yourDatabase

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325276812&siteId=291194637