在 Linux 上配置 MongoDB 授权(用户名/密码登录)一般包含以下步骤:
MongoDB 默认可能未开启认证,需要修改配置文件(通常是 /etc/mongod.conf)。
sudo vi /etc/mongod.conf
在文件中添加或修改以下内容:
security:
authorization: enabled
示例(YAML 格式注意缩进):
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
net:
port: 27017
bindIp: 127.0.0.1
security:
authorization: enabled
保存后重启 MongoDB:
sudo systemctl restart mongod
如果你还没开启
authorization,可以直接连接:
mongo
use admin
db.createUser({
user: "admin",
pwd: "yourpassword",
roles: [ { role: "root", db: "admin" } ]
})
mongo -u admin -p yourpassword --authenticationDatabase admin
或在 mongo shell 中:
use admin
db.auth("admin", "yourpassword")
use mydb
db.createUser({
user: "test",
pwd: "test123",
roles: [
{ role: "readWrite", db: "mydb" }
]
})
登录方式:
mongo -u test -p test123 --authenticationDatabase mydb
| 角色 | 说明 |
|---|---|
| root | 超级管理员 |
| read | 只读 |
| readWrite | 读写 |
| dbAdmin | 数据库管理 |
| userAdmin | 用户管理 |
--authenticationDatabase 正确sudo systemctl status mongod
journalctl -u mongod
authorizationuse admin
db.changeUserPassword("admin", "newpass")
如果你需要 Docker 环境 或 副本集(Replica Set)授权配置,也可以告诉我。