在 Debian 下连接 MongoDB,通常分为 本地连接 和 远程连接 两种情况。下面按最常见的使用方式说明。
sudo systemctl status mongod
如果未启动:
sudo systemctl start mongod
sudo systemctl enable mongod
mongosh(推荐)MongoDB 新版本默认使用 mongosh 客户端。
mongosh
连接成功后会看到类似:
test>
mongosh mydb
如果是老版本 MongoDB(≤4.4):
mongo
mongosh "mongodb://localhost:27017"
mongosh "mongodb://user:password@localhost:27017/mydb"
mongosh "mongodb://user:password@localhost:27017/mydb?authSource=admin"
编辑配置文件:
sudo nano /etc/mongod.conf
修改 bindIp:
net:
port: 27017
bindIp: 0.0.0.0
⚠️ 生产环境建议只开放指定 IP,不要直接
0.0.0.0
重启服务:
sudo systemctl restart mongod
sudo ufw allow 27017
mongosh "mongodb://user:password@远程IP:27017/mydb"
Connection refusedbindIp 限制authSource 不正确创建用户示例:
use admin
db.createUser({
user: "admin",
pwd: "password",
roles: [{ role: "root", db: "admin" }]
})
db.runCommand({ connectionStatus: 1 })
如果你愿意,可以告诉我:
我可以给你更精确的命令。