下面以 Debian + MongoDB(以 6.x / 7.x 为例) 说明如何配置权限(用户认证)。如果你用的是老版本(4.x / 5.x),步骤也基本一致。
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:
authorization: enabled
⚠️ 注意:
security: 前面不能有空格authorization 缩进 2 个空格保存后退出。
sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin
输入密码即可。
mongosh
use admin
db.auth("admin", "StrongPassword123")
假设你要用一个数据库 mydb:
use mydb
db.createUser({
user: "myuser",
pwd: "MyUserPwd456",
roles: [{ role: "readWrite", db: "mydb" }]
})
连接示例:
mongosh -u myuser -p --authenticationDatabase mydb
| 角色 | 说明 |
|---|---|
root |
超级管理员 |
readWrite |
读写某数据库 |
read |
只读 |
dbAdmin |
数据库管理 |
userAdmin |
用户管理 |
mongosh
如果没登录就执行命令报错:
not authorized on admin to execute command
✅ 说明权限已生效
sudo ufw allow from 你的IP to any port 27017
/etc/mongod.confauthorization如果你愿意,可以告诉我:
我可以给你更精确的配置方案。