mcpField
U
using-document-databases

using-document-databases

github.com/ancoleman数据与数据库52564 次安装46 周前更新
代码仓库

关于 using-document-databases

面向应用开发者的数据技能,指导选择和实现 MongoDB、DynamoDB 与 Firestore 等文档数据库。内容涵盖模式设计、索引、查询性能,并提供多语言示例与验证脚本。

主要功能

  1. 01数据库选型指导
  2. 02嵌入与引用模式设计
  3. 03索引策略与覆盖验证
  4. 04MongoDB 聚合管道模式
  5. 05多语言实现示例
  6. 06模式分析与索引脚本

适用场景

  1. 01为灵活模式应用选择文档数据库
  2. 02设计一对多及多对多数据结构
  3. 03检查查询索引覆盖情况
  4. 04构建实时或事件记录应用

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/ancoleman/ai-design-components --skill using-document-databases

安装后在 Claude Code 中输入/using-document-databases确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

outputs.yaml
README.md
examples/dynamodb-serverless/
handler.py
serverless.yml
examples/firestore-react/
README.md
examples/mongodb-fastapi/
main.py
requirements.txt
examples/mongodb-nextjs/
README.md
references/
aggregation-patterns.md
anti-patterns.md
common-patterns.md
dynamodb.md
firestore.md
indexing-strategies.md
mongodb.md
performance.md
schema-design-patterns.md
skill-integrations.md
scripts/
validate_indexes.py

详细介绍

文档数据库实现

为 Python、TypeScript、Rust 和 Go 中的灵活架构应用选择并实现 NoSQL 文档数据库的指南。

何时使用此技能

当应用需要以下特性时,使用文档数据库:

  • 灵活的架构 - 数据模型快速演进,无需迁移
  • 嵌套结构 - 类似 JSON 的层级数据
  • 水平扩展 - 内置分片和复制
  • 提升开发效率 - 对象到数据库的映射,无需 ORM 的复杂性

数据库选择

快速决策框架
DEPLOYMENT ENVIRONMENT?
├── AWS-Native Application → DynamoDB
│   ✓ Serverless, auto-scaling, single-digit ms latency
│   ✗ Limited query flexibility
│
├── Firebase/GCP Ecosystem → Firestore
│   ✓ Real-time sync, offline support, mobile-first
│   ✗ More expensive for heavy reads
│
└── General-Purpose/Complex Queries → MongoDB
    ✓ Rich aggregation, full-text search, vector search
    ✓ ACID transactions, self-hosted or managed
数据库对比
数据库最适合延迟最大条目大小查询语言
MongoDB通用场景、复杂查询1-5ms16MBMQL(功能丰富)
DynamoDBAWS 无服务器架构、可预测的性能<10ms400KBPartiQL(功能有限)
Firestore实时应用、移动端优先50-200ms1MBFirebase 查询

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

架构设计模式

嵌入与引用

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

快速指南:

关系模式示例
一对少嵌入用户地址(最多 2-3 个)
一对多混合博客文章 → 评论
一对百万引用用户 → 事件(日志记录)
多对多引用产品 ↔ 类别
嵌入示例(MongoDB)
// User with embedded addresses
{
  _id: ObjectId("..."),
  email: "[email protected]",
  name: "Jane Doe",
  addresses: [
    {
      type: "home",
      street: "123 Main St",
      city: "Boston",
      default: true
    }
  ],
  preferences: {
    theme: "dark",
    notifications: { email: true, sms: false }
  }
}
引用示例(电商)
// Orders reference products
{
  _id: ObjectId("..."),
  userId: ObjectId("..."),
  items: [
    {
      productId: ObjectId("..."),      // Reference
      priceAtPurchase: 49.99,          // Denormalize (historical)
      quantity: 2
    }
  ],
  totalAmount: 99.98
}

适合反规范化的场景:

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

索引策略

MongoDB 索引类型
// 1. Single field (unique email)
db.users.createIndex({ email: 1 }, { unique: true })

// 2. Compound index (ORDER MATTERS!)
db.orders.createIndex({ status: 1, createdAt: -1 })

// 3. Partial index (index subset)
db.orders.createIndex(
  { userId: 1 },
  { partialFilterExpression: { status: { $eq: "pending" }}}
)

// 4. TTL index (auto-delete after 30 days)
db.sessions.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 2592000 }
)

// 5. Text index (full-text search)
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 实时功能

前端技能集成

  • Media Skill - 使用 MongoDB GridFS 配合元数据存储大型文件
  • AI Chat Skill - 使用 MongoDB Atlas Vector Search 进行语义对话检索
  • Feedback Skill - 使用 DynamoDB 和 TTL 高吞吐地记录事件

集成示例见: references/skill-integrations.md

性能优化

关键实践:

  • 始终为查询筛选条件使用索引(通过 .explain() 验证)
  • 使用连接池(在多个请求间复用客户端)
  • 避免在生产环境中扫描整个集合

完整优化指南见: references/performance.md

常见模式

分页: 对大型数据集使用基于游标的分页(推荐优先于偏移量) 软删除: 使用时间戳标记为已删除,而不是移除 审计日志: 在文档中存储版本历史

实现详情请参阅: references/common-patterns.md

验证和脚本

验证索引覆盖率
# Run validation script
python scripts/validate_indexes.py --db myapp --collection orders

# Output:
# ✓ Query { status: "pending" } covered by index status_1
# ✗ Query { userId: "..." } missing index - add: { userId: 1 }
模式分析
# Analyze schema patterns
python scripts/analyze_schema.py --db myapp

# Output:
# Collection: users
# - Average document size: 2.4 KB
# - Embedding ratio: 87% (addresses, preferences)
# - Reference ratio: 13% (orderIds)
# Recommendation: Good balance

应避免的反模式

无界数组: 限制嵌入式数组(大型集合请使用引用) 过度索引: 仅为查询字段建立索引(索引会拖慢写入) DynamoDB 扫描: 始终使用带分区键的 Query(避免 Scan)

详细的反模式请参阅: 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 - 嵌入与引用的选择
  • 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/

评论

支持 Markdown