温馨提示×

centos mongodb怎么设用户

小樊
35
2026-10-14 15:58:15
栏目: 云计算

在 CentOS 上给 MongoDB 设置用户,通常分为 启用鉴权 → 创建管理员 → 创建业务用户 → 用账号连接 几个步骤。下面以 MongoDB 4.x/5.x/6.x(systemd 方式) 为例。


一、确认 MongoDB 已安装并运行

systemctl status mongod

如果没启动:

systemctl start mongod
systemctl enable mongod

二、先不验证,进入 MongoDB

mongo

(MongoDB 6+ 可能是 mongosh)


三、创建管理员用户(重要)

在 admin 数据库创建超级管理员:

use admin
db.createUser({
  user: "root",
  pwd: "StrongPassword",
  roles: [ { role: "root", db: "admin" } ]
})

四、开启 MongoDB 鉴权

编辑配置文件:

vi /etc/mongod.conf

找到并修改:

security:
  authorization: enabled

重启 MongoDB:

systemctl restart mongod

五、用管理员登录

mongo -u root -p --authenticationDatabase admin

六、创建业务数据库和用户

例如创建一个 testdb 的数据库和用户:

use testdb
db.createUser({
  user: "testuser",
  pwd: "Test@123",
  roles: [
    { role: "readWrite", db: "testdb" }
  ]
})

七、使用业务用户连接

mongo -u testuser -p --authenticationDatabase testdb

或在连接字符串中:

mongodb://testuser:Test@123@localhost:27017/testdb

八、常用角色说明

  • root:超级权限
  • readWrite:读写当前库
  • read:只读
  • dbAdmin:库管理
  • clusterAdmin:集群管理

九、常见问题

1. 忘记开鉴权也能连?

默认没开 authorization 是不验证的。

2. 登录提示认证失败?

确认:

  • 用户名/密码正确
  • authenticationDatabase 正确(管理员是 admin)

3. CentOS 防火墙

firewall-cmd --add-port=27017/tcp --permanent
firewall-cmd --reload

如果你告诉我:

  • MongoDB 版本
  • 是否只本地使用
  • 是否需要远程访问

我可以给你更精确的配置。

0 踩