当前位置: 首页 > Skill >

MongoDB

MongoDB

1.0.1 2026.11.27 浏览:802
获取Skill文件查看使用说明
作者:沈景许可证:
本文目录展开

When to Use

User needs MongoDB expertise — from schema design to production optimization. Agent handles document modeling, indexing strategies, aggregation pipelines, consistency patterns, and scaling.

Quick Reference

Topic File
Schema design patterns schema.md
Index strategies indexes.md
Aggregation pipeline aggregation.md
Production configuration production.md

Schema Design Philosophy

  • Embed when data is queried together and doesn't grow unboundedly
  • Reference when data is large, accessed independently, or many-to-many
  • Denormalize for read performance, accept update complexity—no JOINs means duplicate data
  • Design for your queries, not for normalized elegance

Document Size Traps

  • 16MB max per document—plan for this from day one; use GridFS for large files
  • Arrays that grow infinitely = disaster—use bucketing pattern instead
  • BSON overhead: field names repeated per document—short names save space at scale
  • Nested depth limit 100 levels—rarely hit but exists

Array Traps

  • Arrays > 1000 elements hurt performance—pagination inside documents is hard
  • $push without $slice = unbounded growth; use $push: {$each: [...], $slice: -100}
  • Multikey indexes on arrays: index entry per element—can explode index size
  • Can't have multikey index on more than one array field in compound index

$lookup Traps

  • $lookup performance degrades with collection size—no index on foreign collection (until 5.0)
  • One $lookup per pipeline stage—nested lookups get complex and slow
  • $lookup with pipeline (5.0+) can filter before joining—massive improvement
  • Consider: if you $lookup frequently, maybe embed instead

Index Strategy

  • ESR rule: Equality fields first, Sort fields next, Range fields last
  • MongoDB doesn't do efficient index intersection—single compound index often better
  • Only one text index per collection—plan carefully; use Atlas Search for complex text
  • TTL index for auto-expiration: {createdAt: 1}, {expireAfterSeconds: 86400}

Consistency Traps

  • Default read/write concern not fully consistent—{w: "majority", readConcern: "majority"} for strong
  • Multi-document transactions since 4.0—but add latency and lock overhead; design to minimize
  • Single-document operations are atomic—exploit this by embedding related data
  • retryWrites: true in connection string—handles transient failures automatically

Read Preference Traps

  • Stale reads on secondaries—replication lag can be seconds
  • nearest for lowest latency—but may read stale data
  • Write always goes to primary—read preference doesn't affect writes
  • Read your own writes: use primary or session-based causal consistency

ObjectId Traps

  • Contains timestamp: ObjectId.getTimestamp()—extract creation time without extra field
  • Roughly time-ordered—can sort by _id for creation order without createdAt
  • Not random—predictable if you know creation time; don't rely on for security tokens

Performance Mindset

  • explain("executionStats") shows actual execution—not just theoretical plan
  • totalDocsExamined vs nReturned ratio should be ~1—otherwise index missing
  • COLLSCAN in explain = full collection scan—add appropriate index
  • Covered queries: IXSCAN + totalDocsExamined: 0—all data from index

Aggregation Philosophy

  • Pipeline stages are transformations—think of data flowing through
  • Filter early ($match), project early ($project)—reduce data volume ASAP
  • $match at start can use indexes; $match after $unwind cannot
  • Test complex pipelines stage by stage—build incrementally

Common Mistakes

  • Treating MongoDB as "schemaless"—still need schema design; just enforced in app not DB
  • Not adding indexes—scans entire collection; every query pattern needs index
  • Giant documents via array pushes—hit 16MB limit or slow BSON parsing
  • Ignoring write concern—data may appear written but not persisted/replicated

相关文章

更多
PHP连接MongoDB失败或超时的常见原因与解决

排查 PHP 连接 MongoDB 失败或超时,核心在于确认 mongodb.so 扩展是否已加载、驱动版本与 MongoDB Server 的兼容性,以及 URI 中的认证参数和防火墙策略。若报错为 Class 'MongoDB\Driver\Manager' not found ,需重新安装扩展;若连接超时,通常由

2026.03.23 850
PHP MongoDB持久化连接与连接池配置优化

在 PHP 中操作 MongoDB 时,开启持久化连接( Persistent Connections )并配合适当的连接池配置,可以显著减少 TCP 握手和认证开销,提升高并发场景下的响应速度。核心做法是在 MongoDB URI 中添加 connect=direct 或 connect=replicaSet 参数,

2025.05.20 804
PHP安装MongoDB驱动及建立数据库连接

安装 mongodb 扩展并调用 MongoDB\Client 构造函数传入连接字符串即可建立连接。

2026.05.10 596
PHP中怎么使用MongoDB聚合管道进行数据统计

在 PHP 中使用 MongoDB 聚合管道进行数据统计,核心方法是调用 MongoDB\Driver\Manager 实例的 executeCommand 方法,传入包含 aggregate 、 pipeline 和 collection 字段的命令文档。直接构建符合 MongoDB Shell 语法的 PHP 数组

2025.05.06 532
PHP实现MongoDB数据的增删改查操作示例

使用 MongoDB\Driver 扩展实现增删改查,核心是构建 MongoDB\Driver equest 并交由 MongoDB\DriverulkWrite 或 MongoDB\Driver eadPreference 执行。

2026.04.16 470
Skill 文件
  • SKILL.md
    • When to Use
    • Quick Reference
    • Schema Design Philosophy
    • Document Size Traps
    • Array Traps
    • $lookup Traps
    • Index Strategy
    • Consistency Traps
    • Read Preference Traps
    • ObjectId Traps
    • Performance Mindset
    • Aggregation Philosophy
    • Common Mistakes
  • 项目或源文件

相关 Skill

更多
mongodb-query mongodb-query 用于调试和故障排查,查询MongoDB数据库。用户需要时可以: (1) 列出所有数据库; (2) 列出数据库中的集合; (3) 执行MongoDB查询或命令。
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...