在 CentOS 上给 MongoDB 设置用户,通常分为 启用鉴权 → 创建管理员 → 创建业务用户 → 用账号连接 几个步骤。下面以 MongoDB 4.x/5.x/6.x(systemd 方式) 为例。
systemctl status mongod
如果没启动:
systemctl start mongod
systemctl enable mongod
mongo
(MongoDB 6+ 可能是 mongosh)
在 admin 数据库创建超级管理员:
use admin
db.createUser({
user: "root",
pwd: "StrongPassword",
roles: [ { role: "root", db: "admin" } ]
})
编辑配置文件:
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:集群管理默认没开 authorization 是不验证的。
确认:
authenticationDatabase 正确(管理员是 admin)firewall-cmd --add-port=27017/tcp --permanent
firewall-cmd --reload
如果你告诉我:
我可以给你更精确的配置。