mongodb-expert
Designs MongoDB schemas, indexes, and aggregation pipelines that perform - embed-vs-reference decision rules, the 16MB document limit, ESR compound-index ordering, explain-plan verification, and operational settings for replica sets and sharding. Use when someone asks "should I embed or reference this", "why is my Mongo query slow", "design a MongoDB schema for X", "how do I structure this aggregation pipeline", or "what should my shard key be". Do NOT use for relational or SQL schema design - use database-schema instead; for tuning SQL queries use sql-query-optimizer; for Postgres-on-Supabase work use supabase-expert.
- License 许可
- MIT
- 最近更新
- 2026-10-14
- Stars
- ★ 25
- Forks
- 3
01 前言 Front Matter
- name
- mongodb-expert
- metadata
- { "title": "MongoDB Expert" }
- description
- Designs MongoDB schemas, indexes, and aggregation pipelines that perform - embed-vs-reference decision rules, the 16MB document limit, ESR compound-index ordering, explain-plan verification, and operational settings for replica sets and sharding. Use when someone asks "should I embed or reference this", "why is my Mongo query slow", "design a MongoDB schema for X", "how do I structure this aggregation pipeline", or "what should my shard key be". Do NOT use for relational or SQL schema design - use database-schema instead; for tuning SQL queries use sql-query-optimizer; for Postgres-on-Supabase work use supabase-expert.
03 SKILL.md 正文
MongoDB Expert
Model data, index it, and query it the MongoDB way: around access patterns, not normalization. The costly mistake this skill prevents is a relationally-normalized schema ported into Mongo - a design that forces application-side joins on every read and, in the opposite failure, unbounded embedded arrays that grow until documents hit the 16MB limit and writes start failing in production.
Operating procedure
Schema first, indexes second, pipelines third - indexes serve queries, and queries are determined by the schema, so working backwards wastes every downstream decision.
Step 1: Gather inputs
- The top read and write patterns, ranked by frequency: which entities are fetched together, filtered by what, sorted by what.
- Cardinality and growth of every one-to-many relationship: bounded ("an order has 5-50 line items") or unbounded ("a user accrues events forever"). Label estimates as guesses.
- Read/write ratio per collection and expected document counts.
- Deployment shape: replica set or sharded cluster, and durability requirements.
Step 2: Decide embed vs reference per relationship
Apply these rules in order; the first that fires decides.
- Accessed together and the child side is bounded (a known, modest maximum) → embed. One read serves the whole query.
- Child is unbounded, large, or shared by multiple parents → reference. Unbounded arrays are the canonical anti-pattern: array growth relocates documents, bloats indexes, and marches toward the 16MB document cap.
- Need the most recent few children with the parent, but the full set is unbounded → subset pattern: embed the latest N (say 10) and keep the full history in a referenced collection.
- High-volume time-ordered children (events, readings) → bucket pattern: one document per parent per time window (for example, per hour) holding an array capped by the window.
Budget documents well under 16MB - treat a typical document above a few hundred KB as a design smell to justify, not a limit to approach.
Step 3: Index for the actual queries
Indexes are the single biggest performance lever.
- Follow the ESR rule for compound indexes: Equality fields first, then Sort fields, then Range fields. A query filtering on customerId and sorting by createdAt is fully served by
{ customerId: 1, createdAt: -1 }. - Verify with
explain("executionStats"): require IXSCAN, never COLLSCAN, on any hot path; check thattotalDocsExaminedis close tonReturned- a 100:1 ratio means the index is not selective for that query. - Use partial indexes to index only the documents a query can match (for example, only
status: "active"). - Use covered queries - projection limited to indexed fields - to skip fetching documents entirely.
- Cap the index count: every index taxes every write. If a collection carries more than 5-8 indexes, audit for unused ones with
$indexStats.
Step 4: Build pipelines that shrink early
Filter early so indexes apply and less data flows downstream:
db.orders.aggregate([
{ $match: { status: "shipped", createdAt: { $gte: start } } },
{ $group: { _id: "$customerId", total: { $sum: "$amount" }, n: { $sum: 1 } } },
{ $sort: { total: -1 } },
{ $limit: 100 }
])
- Place
$matchand$projectas early as possible; only a leading$matchcan use indexes. $lookupis a join - index the foreign field or the lookup degenerates to a per-document collection scan.- Use
$facetto compute multiple aggregations in one pass over the data. - Stages have memory limits; pass
{ allowDiskUse: true }for large groupings and sorts, and treat needing it on a hot path as a signal to pre-aggregate.
Step 5: React to changes with change streams
const stream = db.collection("orders").watch([
{ $match: { operationType: "insert" } }
])
for await (const change of stream) { handle(change.fullDocument) }
Persist the resume token and resume from it after failures, or events are silently lost. Change streams require a replica set.
Step 6: Set the operational posture
- Run a replica set for durability; use write concern
w: "majority"for anything you cannot afford to lose on failover. - Choose read concern to match consistency needs; defaults favor speed over read-your-own-writes.
- Shard on a high-cardinality key that distributes writes evenly. Never shard on a monotonically increasing key (timestamps, ObjectId) - all inserts land on one shard. Use a hashed or compound key instead.
- Enable the database profiler (or slow-query log) with a threshold around 100ms and review it routinely.
- Use multi-document transactions only when truly needed; single-document operations are already atomic, and a schema that embeds what changes together rarely needs transactions at all.
Worked artifact: schema pair, bad vs good
The domain: an e-commerce store with users, orders, and order events (status changes, notifications - unbounded over time).
Bad - relational normalization ported into Mongo, plus an unbounded embed:
// users: { _id, name, email }
// orders: { _id, userId, status,
// itemIds: [ObjectId, ...], // items referenced -> N+1 reads
// events: [{ ts, type, note }, ...] // UNBOUNDED array
// }
// items: { _id, sku, name, price }
Rendering one order page costs 1 read for the order, N reads for the items, and the events array grows forever - busy orders churn toward the 16MB cap, every event push rewrites a growing document, and the events field bloats every index that includes it.
Good - embed the bounded, reference the unbounded, subset the recent:
// orders: {
// _id, userId, status, createdAt,
// items: [ // EMBEDDED: bounded (5-50), read together,
// { sku, name, price, qty } // price snapshotted at purchase time
// ],
// recentEvents: [ // SUBSET: latest 10 only, capped with
// { ts, type } // $push + $slice on every insert
// ]
// }
// order_events: { // REFERENCED: unbounded full history
// _id, orderId, ts, type, note // index: { orderId: 1, ts: -1 }
// }
// users: { _id, name, email } // shared by many orders -> referenced
One read renders the order page (items and recent activity embedded); the full audit trail lives in order_events, indexed for the rare "show all history" query; documents stay small and stable-sized. Items embed a price snapshot deliberately - the order must show what was paid, not the current catalog price.
Deliverable
Produce a schema and query design document containing: each relationship with its embed/reference/subset/bucket ruling and the rule that decided it, the collection sketches with representative documents, the index list with the query each serves and its ESR ordering, explain-plan verification notes for the hot paths, and the operational settings (write concern, shard key if sharded, profiler threshold).
Do NOT
- Do not normalize by habit; every referenced relationship is a join the application pays for on each read.
- Do not embed unbounded arrays; use the subset or bucket pattern before growth forces an emergency migration.
- Do not order compound index fields by intuition; violate ESR and the index serves the filter but not the sort, forcing in-memory sorts.
- Do not ship a query whose explain plan shows COLLSCAN on a hot path, or whose docs-examined dwarfs docs-returned.
- Do not shard on a monotonically increasing key; a single hot shard absorbs all writes.
- Do not reach for transactions to patch a schema that split data which changes together - restructure instead.
Quality bar
The design ships only when: every relationship's embed/reference decision cites cardinality and access pattern, not preference; no document can grow without bound under any workload; every hot query shows IXSCAN with docs-examined near docs-returned in explain("executionStats"); leading $match stages hit indexes; and the write-concern and shard-key choices are stated with their failure trade-offs.
04 同仓库更多 Skills
有氧运动计划
zone-2-cardio-plan
当有人要求制定稳态有氧训练计划、进行有氧基础训练或达到第二区间、安排轻松或耐力型的每周有氧训练、按心率区间训练,或提高静息心率、最大摄氧量或耐力时,可以使用此方案。该方案构建了一个包含训练计划结构、训练方式选择和进度安排的心率区间有氧训练模块。本方案仅提供一般健身指导,不构成医疗建议。请勿用于设计力量或举重训练计划(请使用力量训练计划)、高强度间歇训练 (HIIT) 或循环训练(请使用体能训练和 HIIT 计划),或灵活性/柔韧性训练(请使用灵活性训练计划)。
youtube-script-writer
Writes retention-engineered long-form YouTube scripts on a hook/body/payoff architecture - a first-30-seconds hook that survives the retention cliff, a beat-sheet body with mini-hooks and bridges, timed pattern interrupts, and a payoff that over-delivers - with B-roll and editing cues marked inline. Use when someone says "script my next video", "my retention graph dies at the start", "tighten this draft", or "outline a video on X". Do NOT use for the 3-second opener of TikTok, Reels, or Shorts - use video-hook-writer instead; do NOT use for spoken voiceover synced to on-screen tutorial actions - use narration-script instead; do NOT use for a sales demo built on a buyer's discovery notes - use demo-script instead; do NOT use to design the thumbnail and title - use thumbnail-concept instead.
win-back-campaign
Designs segmented win-back email sequences for dormant users - dormancy tiers, a three-beat sequence with a single proportional incentive, and a suppression rule - and measures success by re-activation, not opens. Use when someone says "our users went quiet", "design a win-back campaign", "how do I re-engage lapsed customers", "should we email people who haven't logged in for months", or lifecycle messaging has stopped landing with a lapsed segment. Do NOT use for recovering an unfinished checkout - use abandoned-cart-sequence instead. Do NOT use for diagnosing and fixing why active customers cancel - use churn-reduction instead. Do NOT use for building always-on onboarding or nurture flows - use email-drip-builder instead.
wikipedia-style
Writes neutral, verifiable, encyclopedic prose following Wikipedia's core content policies and manual of style - NPOV, inline citations, notability-backed claims, and a strict ban on promotional language. Use when someone asks "write this like a Wikipedia article", "draft a Wikipedia page for this company or person", "make this neutral and encyclopedic", or "why does my article draft keep getting rejected". Do NOT use for persuasive or opinion writing - use op-ed-writer instead; for thesis-driven academic papers, use academic-essay; for verifying claims in existing text, use fact-checker.
whitepapers
Structures and writes authoritative B2B whitepapers - a standalone executive summary, a data-sized problem statement, methodology, evidence-driven findings, recommendations, and a soft call to action - flagging every claim that needs a real citation. Use when a marketer asks "write a whitepaper on this topic", "turn our research into a lead-gen asset", "make this credible enough for executives", or a draft reads like a product pitch instead of analysis. Do NOT use for customer-story-driven proof - use case-study-builder instead; for policy audiences, use policy-brief.
white-space-analysis
Finds unmet market gaps by ranking jobs-to-be-done on importance versus satisfaction, overlaying them against current solutions and workarounds, and validating that each gap is real, winnable, and worth winning. Use when someone asks "where are the gaps in this market", "what's underserved here", "where should we play next", or is hunting for product, feature, or market-entry opportunities. Do NOT use for profiling competitors and building battle cards - use competitive-intelligence instead; for putting a dollar figure on an identified opportunity - use market-sizing instead; for extracting jobs-to-be-done from raw customer interviews - use jtbd-extractor instead.