文档数据库实施技能Skill using-document-databases

本技能提供文档数据库的选择、设计和优化指南,适用于需要灵活数据模式的应用开发,如内容管理、用户档案等。涵盖主流文档数据库MongoDB、DynamoDB和Firestore,包括模式设计、索引策略、聚合管道等关键技术。关键词:文档数据库、MongoDB、DynamoDB、Firestore、灵活模式、索引优化、聚合管道、NoSQL。

后端开发 0 次安装 0 次浏览 更新于 3/23/2026

name: 使用文档数据库 description: 文档数据库实施,适用于灵活模式应用。在构建内容管理、用户档案、目录或事件日志时使用。涵盖MongoDB(主要)、DynamoDB、Firestore、模式设计模式、索引策略和聚合管道。

文档数据库实施

指导 NoSQL 文档数据库的选择和实施,适用于跨 Python、TypeScript、Rust 和 Go 的灵活模式应用。

何时使用此技能

使用文档数据库当应用需要:

  • 灵活模式 - 数据模型快速演变而无需迁移
  • 嵌套结构 - JSON 类层次数据
  • 水平扩展 - 内置分片和复制
  • 开发速度 - 对象到数据库映射无 ORM 复杂性

数据库选择

快速决策框架

部署环境?
├── AWS 原生应用 → DynamoDB
│   ✓ 无服务器,自动扩展,单位数毫秒延迟
│   ✗ 查询灵活性有限
│
├── Firebase/GCP 生态系统 → Firestore
│   ✓ 实时同步,离线支持,移动优先
│   ✗ 重度读取更昂贵
│
└── 通用目的/复杂查询 → MongoDB
    ✓ 丰富聚合,全文搜索,向量搜索
    ✓ ACID 事务,自托管或托管

数据库比较

数据库 最适合 延迟 最大项 查询语言
MongoDB 通用目的,复杂查询 1-5ms 16MB MQL(丰富)
DynamoDB AWS 无服务器,可预测性能 <10ms 400KB PartiQL(有限)
Firestore 实时应用,移动优先 50-200ms 1MB Firebase 查询

查看 references/mongodb.md 获取 MongoDB 详情 查看 references/dynamodb.md 获取 DynamoDB 单表设计 查看 references/firestore.md 获取 Firestore 实时模式

模式设计模式

嵌入 vs 引用

使用 references/schema-design-patterns.md 中的决策矩阵

快速指南:

关系 模式 示例
一对一少 嵌入 用户地址(最多2-3个)
一对多 混合 博客文章 → 评论
一对百万 引用 用户 → 事件(日志)
多对多 引用 产品 ↔ 类别

嵌入示例(MongoDB)

// 用户带嵌入地址
{
  _id: ObjectId("..."),
  email: "user@example.com",
  name: "Jane Doe",
  addresses: [
    {
      type: "home",
      street: "123 Main St",
      city: "Boston",
      default: true
    }
  ],
  preferences: {
    theme: "dark",
    notifications: { email: true, sms: false }
  }
}

引用示例(电子商务)

// 订单引用产品
{
  _id: ObjectId("..."),
  userId: ObjectId("..."),
  items: [
    {
      productId: ObjectId("..."),      // 引用
      priceAtPurchase: 49.99,          // 反规范化(历史)
      quantity: 2
    }
  ],
  totalAmount: 99.98
}

何时反规范化:

  • 频繁一起读取
  • 历史快照(价格、名称)
  • 读密集型工作负载

索引策略

MongoDB 索引类型

// 1. 单字段索引(唯一邮箱)
db.users.createIndex({ email: 1 }, { unique: true })

// 2. 复合索引(顺序重要!)
db.orders.createIndex({ status: 1, createdAt: -1 })

// 3. 部分索引(索引子集)
db.orders.createIndex(
  { userId: 1 },
  { partialFilterExpression: { status: { $eq: "pending" }}}
)

// 4. TTL 索引(30天后自动删除)
db.sessions.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 2592000 }
)

// 5. 文本索引(全文搜索)
db.articles.createIndex({
  title: "text",
  content: "text"
})

索引最佳实践:

  • 为所有查询过滤器添加索引
  • 复合索引顺序:等值 → 范围 → 排序
  • 使用覆盖索引(查询和投影在索引中)
  • 使用 explain() 验证索引使用
  • 使用 Performance Advisor(Atlas)监控

使用脚本验证索引:

python scripts/validate_indexes.py

查看 references/indexing-strategies.md 获取完整指南。

MongoDB 聚合管道

关键运算符: $match(过滤)、$group(聚合)、$lookup(连接)、$unwind(数组)、$project(重塑)

完整管道模式和示例,查看: references/aggregation-patterns.md

DynamoDB 单表设计

使用 PK/SK 模式设计访问模式。在一个表中使用复合键存储多种实体类型。

完整单表设计模式和 GSI 策略,查看: references/dynamodb.md

Firestore 实时模式

使用 onSnapshot() 进行实时监听,使用 Firestore 安全规则进行访问控制。

完整实时模式和安全规则,查看: references/firestore.md

多语言示例

完整实现可在 examples/ 目录找到:

  • examples/mongodb-fastapi/ - Python FastAPI + MongoDB
  • examples/mongodb-nextjs/ - TypeScript Next.js + MongoDB
  • examples/dynamodb-serverless/ - Python Lambda + DynamoDB
  • examples/firestore-react/ - React + Firestore 实时

前端技能集成

  • 媒体技能 - 使用 MongoDB GridFS 进行大文件存储和元数据管理
  • AI 聊天技能 - 使用 MongoDB Atlas Vector Search 进行语义对话检索
  • 反馈技能 - 使用 DynamoDB 进行高吞吐量事件日志记录和 TTL

集成示例,查看: references/skill-integrations.md

性能优化

关键实践:

  • 始终为查询过滤器使用索引(使用 .explain() 验证)
  • 使用连接池(跨请求重用客户端)
  • 避免在生产中进行集合扫描

完整优化指南,查看: references/performance.md

常见模式

分页: 对大数据集使用基于游标的分页(推荐超过偏移量) 软删除: 使用时间戳标记删除而非移除 审计日志: 在文档内存储版本历史

实现详情,查看: references/common-patterns.md

验证和脚本

验证索引覆盖

# 运行验证脚本
python scripts/validate_indexes.py --db myapp --collection orders

# 输出:
# ✓ 查询 { status: "pending" } 被索引 status_1 覆盖
# ✗ 查询 { userId: "..." } 缺少索引 - 添加:{ userId: 1 }

模式分析

# 分析模式模式
python scripts/analyze_schema.py --db myapp

# 输出:
# 集合:用户
# - 平均文档大小:2.4 KB
# - 嵌入比率:87%(地址、偏好)
# - 引用比率:13%(订单ID)
# 推荐:良好平衡

避免的反模式

无界数组: 限制嵌入数组(对大型集合使用引用) 过度索引: 仅索引查询字段(索引减缓写入) DynamoDB 扫描: 始终使用带有分区键的查询(避免扫描)

详细反模式,查看: references/anti-patterns.md

依赖项

Python

# MongoDB
pip install motor pymongo

# DynamoDB
pip install boto3

# Firestore
pip install firebase-admin

TypeScript

# MongoDB
npm install mongodb

# DynamoDB
npm install @aws-sdk/client-dynamodb @aws-sdk/util-dynamodb

# Firestore
npm install firebase firebase-admin

Rust

# MongoDB
mongodb = "2.8"

# DynamoDB
aws-sdk-dynamodb = "1.0"

Go

# MongoDB
go get go.mongodb.org/mongo-driver

# DynamoDB
go get github.com/aws/aws-sdk-go-v2/service/dynamodb

额外资源

数据库特定指南:

  • references/mongodb.md - 完整 MongoDB 文档
  • references/dynamodb.md - DynamoDB 单表模式
  • references/firestore.md - Firestore 实时指南

模式指南:

  • references/schema-design-patterns.md - 嵌入 vs 引用决策
  • references/indexing-strategies.md - 索引优化
  • references/aggregation-patterns.md - MongoDB 管道手册
  • references/common-patterns.md - 分页、软删除、审计日志
  • references/anti-patterns.md - 避免的错误
  • references/performance.md - 查询优化
  • references/skill-integrations.md - 前端技能集成

示例: examples/mongodb-fastapi/, examples/mongodb-nextjs/, examples/dynamodb-serverless/, examples/firestore-react/