MongoDB添加普通用户

  1. 没有管理员用户的话就先建一个

    # /usr/local/mongodb/bin/mongo --host localhost --port 27017
    
    rs:PRIMARY> use admin
    switched to db admin
    rs:PRIMARY> db.createUser({
    ...    "user": "root", 
    ...    "pwd": "密码", 
    ...    "roles": [
    ...            {
    ...                    "role": "userAdminAnyDatabase", 
    ...                    "db": "admin"
    ...            }, 
    ...            {
    ...                    "role": "readWriteAnyDatabase", 
    ...                    "db": "admin"
    ...            }, 
    ...            {
    ...                    "role": "dbAdmin", 
    ...                    "db": "admin"
    ...            }, 
    ...            {
    ...                    "role": "root", 
    ...                    "db": "admin"
    ...            }
    ...    ]
    ... });
    
  2. 生成协同文件传输到集群每个节点

    # openssl rand -base64 512 > /usr/local/mongodb/access.key
    # chmod 0600 /usr/local/mongodb/access.key
    
  3. 修改配置文件

    cat >> /usr/local/mongodb/mongod.conf << EOF
    auth=true
    keyFile=/usr/local/mongodb/access.key
    EOF
    
  4. 重启MongoDB

  5. root用户登录验证

    # /usr/local/mongodb/bin/mongo localhost:27017/admin -u root -p
    
  6. 添加普通用户

    rs:PRIMARY> use 库名
    rs:PRIMARY> db.createUser({
    ...  user:"用户名",
    ...  pwd:"密码",
    ...  roles:[
    ...   {role:"readWrite",db:"库名"}
    ...  ]
    ... });
    
posted @ 2022-08-08 23:21  Charramma  阅读(251)  评论(0编辑  收藏  举报