MongoDB 是目前最流行的 NoSQL 文档数据库之一,以灵活的文档模型、强大的查询能力和原生高可用特性著称。本文将详细介绍在 Ubuntu 22.04 上从零搭建 MongoDB 生产环境的完整流程,涵盖安装配置、安全管理、备份恢复、性能优化及常见问题排查。
一、MongoDB 核心概念
1.1 什么是 MongoDB
MongoDB 是一个基于分布式文件存储的开源数据库系统,采用 BSON(Binary JSON)格式存储数据。与传统关系型数据库不同,MongoDB 使用文档模型替代了行和表的概念:
| 关系型数据库 |
MongoDB |
说明 |
| Database |
Database |
数据库 |
| Table |
Collection |
集合(相当于表) |
| Row |
Document |
文档(相当于行) |
| Column |
Field |
字段 |
| Primary Key |
_id |
自动生成的主键 |
| JOIN |
$lookup |
关联查询 |
1.2 核心特性
- 文档模型:Schema-less 设计,同一集合内文档字段可不同
- 高可用:原生支持副本集(Replica Set),自动故障转移
- 水平扩展:分片集群(Sharding)支持海量数据存储
- 丰富查询:支持范围查询、正则、地理位置、聚合管道等
- 索引支持:单字段、复合、文本、TTL、哈希等多种索引类型
- ACID 事务:4.0+ 支持多文档事务
二、环境准备
2.1 系统要求
1 2 3 4 5 6 7 8 9 10
| cat /etc/os-release
sudo setenforce 0 sudo sed -i 's/^SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
sudo apt update sudo apt install -y gnupg curl wget
|
2.2 MongoDB 版本选择
MongoDB 提供三个发行版本,应根据生产需求选择:
| 版本 | 适用场景 | 特点 |
| MongoDB Community | 开发测试、小规模生产 | 免费开源,核心功能齐全 |
| MongoDB Enterprise | 企业级生产环境 | 额外提供 LDAP/Kerberos 认证、审计、加密等 |
| MongoDB Atlas | 云托管部署 | 全托管服务,自动备份、自动扩缩容 |
本文以 MongoDB 7.0 Community 为例。
三、安装 MongoDB
3.1 通过官方 APT 仓库安装(推荐)
1 2 3 4 5 6 7 8 9 10 11
| curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \ sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] http://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | \ sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt update sudo apt install -y mongodb-org
|
3.2 通过 Docker 安装
如果系统中已安装 Docker,也可以使用 Docker 方式快速部署:
1 2 3 4 5 6 7 8 9 10 11 12 13
| docker pull mongo:7.0
docker run -d \ --name mongodb \ --restart unless-stopped \ -p 27017:27017 \ -v mongodb_data:/data/db \ -v mongodb_config:/data/configdb \ -e MONGO_INITDB_ROOT_USERNAME=admin \ -e MONGO_INITDB_ROOT_PASSWORD=YourStrongPass! \ mongo:7.0
|
3.3 启动与验证
1 2 3 4 5 6 7 8 9
| sudo systemctl start mongod sudo systemctl enable mongod
sudo systemctl status mongod
mongosh --eval "db.runCommand({ ping: 1 })"
|
如果返回 { ok: 1 },说明 MongoDB 已正常运行。
四、配置文件详解
MongoDB 的配置文件位于 /etc/mongod.conf,采用 YAML 格式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| storage: dbPath: /var/lib/mongodb journal: enabled: true wiredTiger: engineConfig: cacheSizeGB: 1
systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log logRotate: reopen
net: port: 27017 bindIp: 127.0.0.1
processManagement: timeZoneInfo: /usr/share/zoneinfo
security: authorization: enabled
|
关键配置说明:
storage.wiredTiger.engineConfig.cacheSizeGB:WiredTiger 存储引擎的缓存大小,默认为 RAM 的 50%,建议物理机不超过 80%
security.authorization:启用后必须创建用户才能访问
net.bindIp:生产环境应绑定内网 IP 或 127.0.0.1,绝不绑定 0.0.0.0
五、用户认证与权限管理
5.1 创建管理员用户
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| mongosh
use admin
db.createUser({ user: "admin", pwd: "YourStrongAdminPass!", roles: [ { role: "root", db: "admin" } ] })
db.createUser({ user: "appuser", pwd: "AppUserPass123!", roles: [ { role: "readWrite", db: "myapp" } ] })
|
5.2 MongoDB 内置角色
| 角色 | 权限范围 | 适用场景 |
| read | 读取指定数据库的所有非系统集合 | 只读应用程序 |
| readWrite | 读写指定数据库的所有非系统集合 | 一般应用 |
| dbAdmin | 数据库管理(索引、Schema、统计) | DBA 日常维护 |
| userAdmin | 用户和角色管理 | 用户管理员 |
| clusterAdmin | 集群管理最大权限 | 集群管理员 |
| readAnyDatabase | 所有数据库只读 | 监控与审计 |
| root | 所有数据库所有权限 | 超级管理员(慎用) |
5.3 连接认证
1 2 3 4 5
| mongosh -u admin -p 'YourStrongAdminPass!' --authenticationDatabase admin
mongosh "mongodb://appuser:AppUserPass123!@localhost:27017/myapp"
|
六、数据库 CRUD 操作入门
6.1 数据库与集合操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| use myapp
show dbs
db.createCollection("users", { capped: false, autoIndexId: true })
show collections
|
6.2 插入文档
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| db.users.insertOne({ name: "张三", email: "zhangsan@example.com", age: 28, tags: ["developer", "mongodb"], address: { city: "北京", district: "海淀" }, createdAt: new Date() })
db.users.insertMany([ { name: "李四", email: "lisi@example.com", age: 32 }, { name: "王五", email: "wangwu@example.com", age: 25 } ])
|
6.3 查询文档
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| db.users.find()
db.users.find({ age: { $gt: 25 } })
db.users.find({}, { name: 1, email: 1, _id: 0 })
db.users.find() .sort({ age: -1 }) .skip(0) .limit(10)
db.users.aggregate([ { $match: { age: { $gte: 18 } } }, { $group: { _id: "$address.city", count: { $sum: 1 }, avgAge: { $avg: "$age" } } }, { $sort: { count: -1 } } ])
|
6.4 更新文档
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| db.users.updateOne( { name: "张三" }, { $set: { age: 29 }, $inc: { loginCount: 1 } } )
db.users.updateMany( { age: { $lt: 20 } }, { $set: { status: "minor" } } )
db.users.replaceOne( { name: "张三" }, { name: "张三", email: "newemail@example.com", age: 29, role: "admin" } )
|
6.5 删除文档
1 2 3 4 5 6 7 8
| db.users.deleteOne({ name: "王五" })
db.users.deleteMany({ age: { $lt: 18 } })
db.users.deleteMany({})
|
七、索引优化
索引是 MongoDB 查询性能的关键,合理的索引设计可将查询时间从秒级降至毫秒级。
7.1 索引类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| db.users.createIndex({ email: 1 })
db.users.createIndex({ status: 1, createdAt: -1 })
db.users.createIndex({ email: 1 }, { unique: true })
db.articles.createIndex({ title: "text", content: "text" })
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 86400 })
db.users.createIndex({ _id: "hashed" })
db.users.createIndex({ optionalField: 1 }, { sparse: true })
|
7.2 索引管理
1 2 3 4 5 6 7 8 9 10 11
| db.users.getIndexes()
db.users.find({ email: "test@example.com" }).explain("executionStats")
db.users.dropIndex("email_1")
db.users.reIndex()
|
7.3 索引设计原则
- ESR 原则:复合索引按 Equality(等值)→ Sort(排序)→ Range(范围)字段顺序创建
- 覆盖查询:索引字段包含查询所需的所有字段,避免回表
- 选择性:优先在高选择性的字段上创建索引(如 email 优于 status)
- 控制数量:每个集合索引数建议不超过 5 个,过多的索引影响写入性能
八、备份与恢复
8.1 使用 mongodump/mongorestore
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| mongodump --uri="mongodb://admin:YourStrongAdminPass!@localhost:27017" \ --out=/backup/mongodb/$(date +%Y%m%d)
mongodump --uri="mongodb://admin:YourStrongAdminPass!@localhost:27017/myapp" \ --out=/backup/mongodb/myapp_$(date +%Y%m%d)
mongorestore --uri="mongodb://admin:YourStrongAdminPass!@localhost:27017" \ /backup/mongodb/20260609
mongorestore --uri="mongodb://admin:YourStrongAdminPass!@localhost:27017" \ --nsInclude="myapp.*" \ /backup/mongodb/20260609
|
8.2 使用 MongoDB Atlas 备份
- 生产环境推荐使用 MongoDB Atlas 的自动连续备份功能
- 支持时间点恢复(PITR),可将数据恢复到任意时间点
- 备份存储在云端,安全可靠
8.3 定时备份脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| #!/bin/bash
BACKUP_DIR="/backup/mongodb" DB_NAME="myapp" MONGO_URI="mongodb://admin:YourStrongAdminPass!@localhost:27017" RETENTION_DAYS=7
mkdir -p $BACKUP_DIR
mongodump --uri="$MONGO_URI" \ --db=$DB_NAME \ --out=$BACKUP_DIR/$(date +%Y%m%d)
tar -czf $BACKUP_DIR/mongodb_$(date +%Y%m%d).tar.gz \ -C $BACKUP_DIR $(date +%Y%m%d)
rm -rf $BACKUP_DIR/$(date +%Y%m%d)
find $BACKUP_DIR -name "*.tar.gz" -mtime +$RETENTION_DAYS -delete
echo "Backup completed: $(date)"
|
配置 crontab 定时执行:
1 2
| 0 2 * * * /bin/bash /usr/local/bin/mongodb-backup.sh
|
九、性能监控与调优
9.1 内置监控工具
1 2 3 4 5 6 7 8 9 10 11
| db.serverStatus()
db.stats()
db.currentOp()
db.killOp(opid)
|
9.2 慢查询分析
1 2 3 4 5 6 7 8 9 10 11 12
|
db.setProfilingLevel(1, { slowms: 100 }) db.setProfilingLevel(2)
db.system.profile.find().sort({ ts: -1 }).limit(10).pretty()
|
9.3 性能调优参数
| 参数 | 推荐值 | 说明 |
| wiredTigerCacheSizeGB | RAM 的 50-60% | WiredTiger 缓存,避免 swap |
| maxIncomingConnections | 65536 | 最大连接数 |
| operationProfiling.slowOpThresholdMs | 100 | 慢查询阈值 |
| storage.journal.commitIntervalMs | 100 | Journal 提交间隔 |
| net.serviceExecutor | adaptive | 线程池模式(adaptive/同步/异步) |
9.4 系统层面调优
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| echo 'never' | sudo tee /sys/kernel/mm/transparent_hugepage/enabled echo 'never' | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
cat >> /etc/rc.local << 'EOF'
echo never > /sys/kernel/mm/transparent_hugepage/enabled echo never > /sys/kernel/mm/transparent_hugepage/defrag EOF chmod +x /etc/rc.local
echo "fs.file-max = 98000" >> /etc/sysctl.conf echo "mongod soft nofile 64000" >> /etc/security/limits.conf echo "mongod hard nofile 64000" >> /etc/security/limits.conf
echo "vm.max_map_count = 1024000" >> /etc/sysctl.conf sysctl -p
|
十、安全加固最佳实践
10.1 网络层安全
- 绑定内网地址:
bindIp: 127.0.0.1, 10.0.0.10
- 配置防火墙:仅允许可信源访问 27017 端口
- 不使用默认端口:可修改为 27018 等非默认端口
- 禁用 HTTP 接口:自 3.6 起已移除,较旧版本需显式关闭
1 2 3
| sudo ufw allow from 10.0.0.0/8 to any port 27017 proto tcp sudo ufw deny 27017
|
10.2 认证层安全
- 始终启用 authentication
- 使用强密码:至少 16 位,含大小写字母、数字、特殊字符
- 遵循最小权限原则:每个应用使用独立的数据库用户
- 启用 TLS/SSL 加密传输
1 2 3 4 5 6
| net: tls: mode: requireTLS certificateKeyFile: /etc/ssl/mongodb.pem CAFile: /etc/ssl/ca.pem
|
10.3 审计日志(Enterprise 版)
1 2 3 4 5 6
| auditLog: destination: file format: JSON path: /var/log/mongodb/audit.log filter: '{ atype: { $in: ["createCollection", "dropCollection", "createUser", "dropUser"] } }'
|
10.4 定期安全检查清单
十一、常见问题排查
11.1 连接失败
1 2 3 4 5 6 7 8 9 10 11
| sudo systemctl status mongod
ss -tlnp | grep 27017
sudo tail -100 /var/log/mongodb/mongod.log
sudo ufw status
|
11.2 内存占用过高
1 2 3 4 5 6 7
| mongosh --eval "db.serverStatus().wiredTiger.cache"
sudo systemctl restart mongod
|
11.3 慢查询
1 2 3 4 5 6 7 8
| mongosh --eval "db.getSiblingDB('myapp').system.profile.find().limit(5).pretty()"
mongosh --eval "db.getSiblingDB('myapp').users.find({email: 'test@test.com'}).explain('executionStats')"
mongosh --eval "db.getSiblingDB('myapp').users.stats().indexSizes"
|
11.4 复制集问题
1 2 3 4 5 6 7 8
| mongosh --eval "rs.status()"
mongosh --eval "rs.printReplicationInfo()"
mongosh --eval "rs.printSecondaryReplicationInfo()"
|
11.5 数据文件损坏修复
1 2 3 4 5 6 7 8
| sudo systemctl stop mongod
mongod --repair --dbpath /var/lib/mongodb
mongorestore --uri="mongodb://localhost:27017" /backup/mongodb/latest
|
十二、生产部署 Checklist
总结
MongoDB 以其灵活的文档模型、强大的查询能力和原生的高可用特性,在 Web 应用、IoT、实时分析等领域广泛应用。本文详细介绍了从环境准备、安装配置、安全管理到生产部署的全链路内容。关键要点总结如下:
- 安全先行:安装完成后立即启用认证、绑定内网地址
- 合理配置:WiredTiger 缓存大小直接影响性能,需根据 RAM 合理配置
- 索引为王:大部分性能问题源于缺少合适的索引,善用 explain() 分析查询
- 备份至上:定期验证备份的可恢复性,做到”能恢复的备份才是真正的备份”
- 监控预警:建立完善的监控体系,提前发现潜在问题
本文由AI辅助生成,内容仅供参考