在 CentOS 上给 MongoDB 配置用户名(启用认证)一般步骤如下:
# 以 MongoDB 6.x 为例
sudo yum install -y mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod
mongo
(MongoDB 6+ 可用 mongosh)
use admin
db.createUser({
user: "admin",
pwd: "YourStrongPassword",
roles: [ { role: "root", db: "admin" } ]
})
sudo vi /etc/mongod.conf
添加或修改:
security:
authorization: enabled
⚠️ 注意缩进(YAML 格式)
sudo systemctl restart mongod
mongo -u admin -p --authenticationDatabase admin
或:
mongosh -u admin -p --authenticationDatabase admin
use mydb
db.createUser({
user: "appuser",
pwd: "AppPassword",
roles: [ { role: "readWrite", db: "mydb" } ]
})
连接:
mongo -u appuser -p --authenticationDatabase mydb
authorization/etc/mongod.conf:
net:
bindIp: 0.0.0.0
⚠️ 生产环境建议限制 IP + 防火墙
如果你告诉我:
我可以给你更精确的步骤。