在 Debian 上设置 MongoDB 权限,核心就是 启用认证(Authentication) 并 创建用户和角色。下面按 生产环境推荐流程 一步一步来(适用于 MongoDB 4.x / 5.x / 6.x,Debian 10/11/12 通用)。
sudo apt update
sudo apt install -y mongodb-org
启动服务:
sudo systemctl start mongod
sudo systemctl enable mongod
mongosh
(老版本可能是 mongo)
use admin
db.createUser({
user: "admin",
pwd: "StrongPassword123",
roles: [{ role: "root", db: "admin" }]
})
✅ root 权限最高,适合管理 MongoDB
退出:
exit
sudo nano /etc/mongod.conf
security 项security:
authorization: enabled
⚠ 注意 YAML 格式,缩进必须是两个空格
sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin
输入密码后登录成功即表示认证生效 ✅
假设你要用一个数据库 mydb
use mydb
db.createUser({
user: "myuser",
pwd: "UserPassword456",
roles: [{ role: "readWrite", db: "mydb" }]
})
| 角色 | 说明 |
|---|---|
| read | 只读 |
| readWrite | 读写 |
| dbAdmin | 数据库管理 |
| userAdmin | 用户管理 |
| root | 超级管理员 |
mongosh "mongodb://myuser:UserPassword456@localhost:27017/mydb"
或应用连接:
mongodb://myuser:UserPassword456@localhost:27017/mydb?authSource=mydb
Authentication failed
✅ 检查:
--authenticationDatabase 是否匹配authorization: enabledauthorization✅ 生产环境建议:
net:
bindIp: 127.0.0.1,192.168.x.x
如果你愿意,可以告诉我:
我可以给你一份 完全适合你场景的 MongoDB 权限配置方案 ✅