Communitygithub.com

mongodb/mongodb-schema-design

MongoDB 模式设计模式与反模式。适用于设计数据模型、审查模式、从 SQL 迁移,或排查由模式问题引起的性能问题。触发词包括“设计模式”、“嵌入 vs 引用”、“MongoDB 数据模型”、“模式审查”、“无限数组”、“一对多”、“树形结构”、“16MB 限制”、“模式验证”、“JSON Schema”、“时间序列”、“模式迁移”、“多态”、“TTL”、“数据生命周期”、“归档”、“索引爆炸”、“不必要的索引”、“近似模式”、“文档版本控制”。

mongodb-schema-design 是什么?

这是一个专门用于 MongoDB 模式设计的技能,提供常见的设计模式与反模式指导,帮助开发者构建高效、可扩展的数据模型。当用户输入与模式设计相关的关键词时,该技能会触发相应的建议和分析,涵盖从基本的数据建模(如嵌入 vs 引用)到高级主题(如多态模式、时间序列、TTL 和文档版本控制)。它特别适用于从 SQL 迁移到 MongoDB 的场景,或排查由于模式设计不当(如无限数组、索引爆炸、16MB 文档大小限制)导致的性能问题。该技能支持主要的 AI 编码代理平台,包括 Claude Code、Cursor 和 Codex,并提供基于最佳实践的代码示例和 JSON Schema 验证指南。通过遵循其建议,开发者可以避免常见陷阱,优化查询性能,并确保数据生命周期的有效管理。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mongodb/agent-skills/tree/main/skills/mongodb-schema-design

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

mongodb-schema-design 是做什么的?

MongoDB 模式设计模式与反模式。适用于设计数据模型、审查模式、从 SQL 迁移,或排查由模式问题引起的性能问题。触发词包括“设计模式”、“嵌入 vs 引用”、“MongoDB 数据模型”、“模式审查”、“无限数组”、“一对多”、“树形结构”、“16MB 限制”、“模式验证”、“JSON Schema”、“时间序列”、“模式迁移”、“多态”、“TTL”、“数据生命周期”、“归档”、“索引爆炸”、“不必要的索引”、“近似模式”、“文档版本控制”。

概述

本技能提供全面指导,帮助您在设计 MongoDB 模式时做出正确决策。涵盖从基础概念(如嵌入与引用)到高级模式(包括多态、时间序列和文档版本控制)的所有内容。

使用场景

  • 从 SQL 迁移:将关系型数据模型转换为 MongoDB 文档模型
  • 性能排查:诊断并修复由模式问题(如无限数组、文档过大)导致的性能瓶颈
  • 模式审查:对现有模式进行审查,识别反模式并提出优化方案
  • 生命周期管理:利用 TTL 索引、归档策略管理数据生命周期

常见模式与反模式

模式/反模式描述适用场景
嵌入 vs 引用决定将相关数据嵌入文档还是通过引用关联一对少数关系适合嵌入,一对多关系适合引用
无限数组数组元素无限制增长,导致文档大小超限应避免,改用分桶模式或引用
树形结构表示层次化数据(如分类、组织架构)使用子节点引用、父节点引用或物化路径
多态模式在同一集合中存储形状不同的文档适用于属性变化较大的场景
时间序列高效存储和查询随时间变化的数据使用时间桶、降采样等策略
文档版本控制跟踪文档的历史版本使用单独的历史集合或软删除

最佳实践

  1. 始终使用模式验证:通过 JSON Schema 确保数据完整性
  2. 避免索引爆炸:仅在查询模式需要的字段上创建索引
  3. 监控文档大小:使用 Object.bsonsize() 检查文档是否接近 16MB 限制
  4. 合理使用 TTL:对自动过期数据设置 TTL 索引,减少手动清理
  5. 测试迁移脚本:在生产环境执行前使用真实数据量测试模式变更

代码示例

嵌入文档(适用于一对少关系)

// 用户及其地址(嵌入)
{
  _id: ObjectId("user123"),
  name: "张三",
  addresses: [
    { street: "长安街", city: "北京", type: "home" },
    { street: "浦东大道", city: "上海", type: "work" }
  ]
}

引用(适用于一对多关系)

// 文章及其评论(引用)
// articles 集合
{
  _id: ObjectId("article456"),
  title: "MongoDB 入门指南",
  comment_ids: [ObjectId("comm1"), ObjectId("comm2")]
}

// comments 集合
{
  _id: ObjectId("comm1"),
  article_id: ObjectId("article456"),
  content: "好文章!",
  author: "李四"
}

模式验证(JSON Schema)

db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email"],
      properties: {
        name: {
          bsonType: "string",
          description: "用户名称,必填"
        },
        email: {
          bsonType: "string",
          pattern: "^.+@.+$",
          description: "合法邮箱地址,必填"
        },
        age: {
          bsonType: "int",
          minimum: 0,
          maximum: 150
        }
      }
    }
  }
})

时间序列数据(使用时间桶)

// 按小时聚合传感器数据
db.sensor_readings.updateOne(
  { sensor_id: "sensor001", hour: ISODate("2023-10-01T00:00:00Z") },
  {
    $push: { readings: { temp: 25.5, timestamp: new Date() } },
    $inc: { count: 1 }
  },
  { upsert: true }
)

相关工具与链接

Individual skills in this repo

This repo contains 5 individual skills — each has its own dedicated page.

mongodb/mongodb-connection

Optimize MongoDB client connection configuration (pools, timeouts, patterns) for any supported driver language. Use this skill when working/updating/reviewing on functions that instantiate or configure a MongoDB client (eg, when calling `connect()`), configuring connection pools, troubleshooting connection errors (ECONNREFUSED, timeouts, pool exhaustion), optimizing performance issues related to connections. This includes scenarios like building serverless functions with MongoDB, creating API endpoints that use MongoDB, optimizing high-traffic MongoDB applications, creating long-running tasks and concurrency, or debugging connection-related failures.

mongodb/mongodb-mcp-setup

Guide users through configuring key MongoDB MCP server options. Use this skill when a user has the MongoDB MCP server installed but hasn't configured the required environment variables, or when they ask about connecting to MongoDB/Atlas and don't have the credentials set up.

mongodb/mongodb-natural-language-querying

Generate read-only MongoDB queries (find) or aggregation pipelines using natural language, with collection schema context and sample documents. Use this skill whenever the user asks to write, create, or generate MongoDB queries, wants to filter/query/aggregate data in MongoDB, asks "how do I query...", needs help with query syntax, or discusses finding/filtering/grouping MongoDB documents. Also use for translating SQL-like requests to MongoDB syntax. Does NOT handle Atlas Search ($search operator), vector/semantic search ($vectorSearch operator), fuzzy matching, autocomplete indexes, or relevance scoring - use search-and-ai for those. Does NOT analyze or optimize existing queries - use mongodb-query-optimizer for that. Does NOT handle aggregation pipelines that involve write operations. Requires MongoDB MCP server.

mongodb/mongodb-query-optimizer

Help with MongoDB query optimization and indexing. Use only when the user asks for optimization or performance: "How do I optimize this query?", "How do I index this?", "Why is this query slow?", "Can you fix my slow queries?", "What are the slow queries on my cluster?", etc. Do not invoke for general MongoDB query writing unless user asks for performance or index help. Prefer indexing as optimization strategy. Use MongoDB MCP when available.

mongodb/mongodb-search-and-ai

Guides MongoDB users through implementing and optimizing Atlas Search (full-text), Vector Search (semantic), and Hybrid Search solutions. Use this skill when users need to build search functionality for text-based queries (autocomplete, fuzzy matching, faceted search), semantic similarity (embeddings, RAG applications), or combined approaches. Also use when users need text containment, substring matching ('contains', 'includes', 'appears in'), case-insensitive or multi-field text search, or filtering across many fields with variable combinations. Provides workflows for selecting the right search type, creating indexes, constructing queries, and optimizing performance using the MongoDB MCP server.

相关技能