duidui_fiber/INSTALL_MONGODB.md
2026-03-27 10:34:03 +08:00

107 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# MongoDB 安装和配置指南
## 一、解决 Docker 镜像拉取问题
### 方法 1: 配置 Docker 镜像加速器(推荐)
**macOS (Docker Desktop)**:
1. 打开 Docker Desktop
2. 进入 Settings -> Docker Engine
3. 添加以下配置:
```json
{
"registry-mirrors": [
"https://docker.mirrors.ustc.edu.cn",
"https://hub-mirror.c.163.com",
"https://mirror.baidubce.com"
]
}
```
4. 点击 "Apply & Restart"
5. 重新拉取镜像:`docker pull mongo:7.0`
**Linux**:
```bash
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": [
"https://docker.mirrors.ustc.edu.cn",
"https://hub-mirror.c.163.com",
"https://mirror.baidubce.com"
]
}
EOF
sudo systemctl restart docker
docker pull mongo:7.0
```
### 方法 2: 使用国内镜像源
```bash
# 使用阿里云镜像
docker pull registry.cn-hangzhou.aliyuncs.com/acs/mongo:7.0
docker tag registry.cn-hangzhou.aliyuncs.com/acs/mongo:7.0 mongo:7.0
# 或使用网易镜像
docker pull hub-mirror.c.163.com/library/mongo:7.0
docker tag hub-mirror.c.163.com/library/mongo:7.0 mongo:7.0
```
## 二、安装 Go MongoDB 驱动
```bash
cd dd_fiber_api
go get go.mongodb.org/mongo-driver/mongo
go get go.mongodb.org/mongo-driver/bson
go get go.mongodb.org/mongo-driver/mongo/options
go mod tidy
```
## 三、启动 MongoDB
```bash
cd dd_fiber_api/deploy
chmod +x mongodb-start.sh mongodb-stop.sh
./mongodb-start.sh
```
## 四、验证连接
```bash
# 进入 MongoDB Shell
docker exec -it mongodb-question mongosh -u admin -p admin123456 --authenticationDatabase admin
# 测试连接
use question_db
db.questions.insertOne({_id: "test", title: "测试题目"})
db.questions.find()
```
## 五、已创建的文件
1.`pkg/database/mongodb.go` - MongoDB 客户端封装
2.`internal/question/dao/question_dao_mongo.go` - 题目 DAO 实现示例
3.`deploy/docker-compose.mongodb.yml` - Docker Compose 配置
4.`deploy/mongodb-start.sh` - 启动脚本(支持自动使用国内镜像)
5.`deploy/mongodb-stop.sh` - 停止脚本
6.`config/config.go` - 已添加 MongoDBConfig
7.`config.yaml` - 已添加 MongoDB 配置示例
## 六、MongoDB 实现优势
相比 MySQLMongoDB 在题库系统中的优势:
1. **文档模型**:天然支持 JSON题目、试卷等复杂结构更直观
2. **数组查询**:标签等数组字段查询更方便
3. **全文搜索**:内置文本索引,支持全文搜索
4. **灵活扩展**:无需预定义表结构,易于扩展
5. **性能优秀**:读性能好,适合读多写少的场景
## 七、注意事项
1. **全文搜索**MongoDB 的文本索引对中文支持有限,可能需要使用 bleve 等第三方库
2. **事务**MongoDB 4.0+ 支持事务,但性能不如 MySQL
3. **数据备份**:定期备份 MongoDB 数据