在 Debian 上连接 MongoDB,一般分两种情况:本地连接 和 远程连接。下面按步骤说明。
sudo systemctl status mongod
如果没启动:
sudo systemctl start mongod
sudo systemctl enable mongod
确认端口(默认 27017):
ss -lntp | grep 27017
mongo
mongosh
成功后会看到:
test>
mongosh "mongodb://用户名:密码@127.0.0.1:27017/数据库名"
示例:
mongosh "mongodb://admin:123456@127.0.0.1:27017/admin"
编辑配置文件:
sudo nano /etc/mongod.conf
修改:
net:
port: 27017
bindIp: 0.0.0.0
⚠️ 生产环境不建议直接
0.0.0.0,应限制 IP
重启:
sudo systemctl restart mongod
sudo ufw allow 27017
mongosh "mongodb://user:password@服务器IP:27017/dbname"
mongoose.connect("mongodb://user:pass@host:27017/dbname");
from pymongo import MongoClient
client = MongoClient("mongodb://user:pass@host:27017/")
如果你愿意,可以告诉我:
我可以给你更精确的连接命令。