MongoDB – 连接

MongoDB 连接全攻略

(MongoDB 8.0+,2025 年最新实践)

连接 MongoDB 是开发、运维、测试的第一步。本文覆盖 所有平台、所有工具、所有场景 的连接方式,带你从 localhostAtlas 云集群,从 mongoshNode.js/Python/Java


一、连接字符串(URI)格式大全

类型格式示例
标准连接mongodb://[user:pass@]host:port[/db]?optionsmongodb://localhost:27017
带认证mongodb://user:pass@host:port/db?authSource=adminmongodb://admin:123@192.168.1.10:27017/company
副本集mongodb://host1,host2,host3/db?replicaSet=rs0mongodb://node1:27017,node2:27017/?replicaSet=rs0
SRV(Atlas)mongodb+srv://user:pass@cluster.xxxxx.mongodb.net/dbmongodb+srv://app:P@ss@cluster0.xxxxx.mongodb.net/shop
TLS/SSL?tls=true&tlsAllowInvalidCertificates=truemongodb://host:27017/?tls=true

注意:密码含特殊字符(如 @, :, /)需 URL 编码
@%40 | :%3A | /%2F


二、命令行连接(mongosh)

1. 本地连接(默认)

mongosh
# 等价于:mongosh "mongodb://127.0.0.1:27017"

2. 远程 + 认证

mongosh -u admin -p YourPass123 --authenticationDatabase admin --host 192.168.1.100

3. 连接字符串方式(推荐)

mongosh "mongodb://admin:YourPass123@192.168.1.100:27017/admin?authSource=admin"

4. Atlas 云连接

mongosh "mongodb+srv://admin:YourPass123@cluster0.xxxxx.mongodb.net/myDB"

三、编程语言连接(Driver)

语言官方 Driver连接代码示例
Node.jsmongodb“`js
const { MongoClient } = require(‘mongodb’);
const uri = “mongodb://admin:pass@localhost:27017/company?authSource=admin”;
const client = new MongoClient(uri);
await client.connect();
const db = client.db(“company”);
| **Python** | `pymongo` | ```python
from pymongo import MongoClient
client = MongoClient("mongodb://admin:pass@localhost:27017/company?authSource=admin")
db = client.company

|
| Java | mongodb-driver-sync | “`java
MongoClient client = MongoClients.create(“mongodb://admin:pass@localhost:27017/company?authSource=admin”);
MongoDatabase db = client.getDatabase(“company”);

| **Go** | `go.mongodb.org/mongo-driver` | ```go
client, _ := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
db := client.Database("company")

|

所有 Driver 都支持标准 URI,推荐使用连接字符串。


四、GUI 工具连接

工具连接方式
MongoDB Compass粘贴完整 URI → Connect
VS Code + MongoDB Extensionmongodb://...mongodb+srv://...
TablePlus新建 → MongoDB → 填写 Host/Port/User
Robo 3T / Studio 3T支持 URI 和表单

五、常见连接场景

1. 本地开发(无认证)

mongosh
# 或
MongoClient("mongodb://localhost:27017")

2. 生产环境(带认证 + TLS)

mongodb://app_user:SecureP@ss2025@db-prod.example.com:27017/shop?
  authSource=admin
  &tls=true
  &tlsCAFile=/path/to/ca.pem
  &retryWrites=true
  &w=majority

3. 副本集高可用连接

mongodb://node1:27017,node2:27017,node3:27017/mydb?
  replicaSet=rs0
  &readPreference=primaryPreferred

4. 分片集群(通过 mongos)

mongodb://mongos1:27017,mongos2:27017/?readPreference=secondary

六、连接参数详解(Query Options)

参数说明推荐值
authSource认证数据库admin
retryWrites自动重试写操作true
w写关注majority
readPreference读偏好primary / secondary
maxPoolSize连接池大小50
connectTimeoutMS连接超时10000
serverSelectionTimeoutMS选主超时30000
tls / ssl启用 TLStrue

推荐生产连接串

mongodb://user:pass@host:27017/db?
  authSource=admin
  &retryWrites=true
  &w=majority
  &readPreference=primaryPreferred
  &tls=true

七、连接池与性能优化

设置建议
连接池大小业务高峰 QPS × 平均响应时间(秒)
心跳频率serverMonitoringMode=stream(新版默认)
负载均衡多个 host 用逗号分隔,Driver 自动轮询
压缩compressors=zlib,snappy 节省带宽
&maxPoolSize=100
&compressors=zstd,snappy,zlib
&zlibCompressionLevel=6

八、故障排查(Connection Issues)

症状检查点解决方案
Connection refused端口、防火墙、mongod 是否运行netstat -tlnp | grep 27017
Authentication failed用户名、密码、authSourcemongosh -u admin -p 测试
Server selection timeout网络、分片节点存活ping + mongosh --host
TLS handshake failed证书路径、过期检查 tlsCAFile
not authorized权限不足检查用户 roles

诊断命令

# 查看 MongoDB 状态
sudo systemctl status mongod

# 查看日志
tail -f /var/log/mongodb/mongod.log

# 测试网络
telnet 192.168.1.100 27017

九、连接安全最佳实践

实践操作
启用认证security.authorization: enabled
使用 TLS生产必须加密传输
IP 白名单防火墙只允许应用服务器
最小权限用户应用只给 readWrite 当前库
密码轮换每 90 天
审计登录开启 auditLog

十、快速连接模板

# 1. 本地开发
mongosh

# 2. 生产应用(Node.js)
const uri = "mongodb://shop_app:Shop2025!@db-prod:27017/shop?authSource=admin&retryWrites=true&w=majority";

# 3. Atlas
mongosh "mongodb+srv://admin:Admin2025!@cluster0.xxxxx.mongodb.net"

# 4. Docker 本地测试
docker run -d -p 27017:27017 --name mongo mongo:8.0
mongosh

总结:连接三要素

graph LR
    A[连接字符串] --> B[认证 authSource=admin]
    B --> C[安全 tls=true]
    C --> D[高可用 replicaSet / SRV]

一句话口诀

“URI 写全,认证必开,TLS 加密,高可用选 SRV”


如需 连接池调优脚本Kubernetes 中连接从 MySQL 迁移连接逻辑多租户连接隔离,欢迎继续提问!

文章已创建 2349

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部