在 Ubuntu 上配置 MongoDB 用户,通常包含以下几个步骤:安装 MongoDB → 启动服务 → 连接 MongoDB → 创建用户 → 开启认证 → 使用用户登录。
下面以 Ubuntu 20.04 / 22.04 + MongoDB 6.x / 7.x 为例说明。
sudo apt update
sudo apt install -y mongodb-org
启动并设置开机自启:
sudo systemctl start mongod
sudo systemctl enable mongod
查看状态:
sudo systemctl status mongod
mongosh
或老版本:
mongo
在 admin 数据库中创建超级管理员:
use admin
db.createUser({
user: "admin",
pwd: "YourStrongPassword",
roles: [
{ role: "root", db: "admin" }
]
})
✅ root 权限最大,适合管理用户和数据库。
比如给 testdb 创建一个读写用户:
use testdb
db.createUser({
user: "testuser",
pwd: "TestPassword123",
roles: [
{ role: "readWrite", db: "testdb" }
]
})
常用角色说明:
read:只读readWrite:读写dbAdmin:数据库管理root:超级管理员编辑配置文件:
sudo vim /etc/mongod.conf
找到 security 部分,改为:
security:
authorization: enabled
如果原本没有,就直接加上。
重启 MongoDB:
sudo systemctl restart mongod
mongosh -u admin -p --authenticationDatabase admin
mongosh
use admin
db.auth("admin", "YourStrongPassword")
mongosh -u testuser -p --authenticationDatabase testdb
show users
或:
db.runCommand({ connectionStatus: 1 })
authorization在 /etc/mongod.conf 中:
net:
bindIp: 0.0.0.0
⚠️ 公网一定要加防火墙 + 强密码。
如果你需要 Docker 方式、MongoDB 副本集用户配置 或 Spring / Node 连接示例,可以继续问我。