在 CentOS 上连接 MongoDB,通常分两种情况:本地连接 和 远程连接。下面按常见场景一步一步说明。
# 查看状态
systemctl status mongod
# 启动
systemctl start mongod
# 开机自启
systemctl enable mongod
MongoDB 6.0 之前:
mongo
MongoDB 6.0 及以后(推荐):
mongosh
连接成功后你会看到类似:
test>
mongosh --port 27017
mongosh test
mongosh -u username -p password --authenticationDatabase admin
编辑配置文件:
vi /etc/mongod.conf
修改如下内容:
net:
port: 27017
bindIp: 0.0.0.0 # 允许所有IP(生产环境建议限制IP)
⚠️ 默认
bindIp: 127.0.0.1,只能本机连接
systemctl restart mongod
firewall-cmd --zone=public --add-port=27017/tcp --permanent
firewall-cmd --reload
mongosh mongodb://远程IP:27017
带账号:
mongosh mongodb://user:password@远程IP:27017/admin
mongodb://IP:27017
或
mongodb://user:password@IP:27017
admin 库--authenticationDatabasemongomongosh如果你愿意,可以告诉我:
我可以给你更精确的操作命令。