在 CentOS 上给 MongoDB 设置账号,一般分为以下几个步骤:启用鉴权 → 创建管理员账号 → 创建业务数据库账号 → 用账号登录。
下面以 MongoDB 4.x / 5.x / 6.x 为例(CentOS 7/8 通用)。
systemctl status mongod
如果没启动:
systemctl start mongod
systemctl enable mongod
mongo
(MongoDB 6+ 可能是 mongosh)
use admin
db.createUser({
user: "root",
pwd: "YourStrongPassword",
roles: [ { role: "root", db: "admin" } ]
})
✅ root 权限最高,仅用于管理
编辑配置文件:
vi /etc/mongod.conf
找到 security 部分,改成:
security:
authorization: enabled
如果是 CentOS 的旧版本,可能写成:
auth = true
保存后重启:
systemctl restart mongod
mongo -u root -p YourStrongPassword --authenticationDatabase admin
例如给 testdb 建一个读写账号:
use testdb
db.createUser({
user: "testuser",
pwd: "TestPassword123",
roles: [
{ role: "readWrite", db: "testdb" }
]
})
mongo -u testuser -p TestPassword123 --authenticationDatabase testdb
或远程连接:
mongo "mongodb://testuser:TestPassword123@localhost:27017/testdb"
| 角色 | 说明 |
|---|---|
| root | 超级管理员 |
| read | 只读 |
| readWrite | 读写 |
| dbAdmin | 数据库管理 |
| userAdmin | 用户管理 |
--authenticationDatabasedb.updateUser("testuser", { pwd: "NewPassword" })
db.dropUser("testuser")
如果你告诉我:
我可以给你更精确的配置示例(包括 防火墙 / bindIp / 副本集鉴权)。