MongoDB Data-Access Rules
SkillDatabases & dataNative-driver, StrictDB, and data-modeling rules for MongoDB. Use whenever writing or modifying queries, writes, indexes, aggregations, upserts, connections, or schema against MongoDB, or any code that touches the data layer. Loads inline so it shapes code as it's written.
Available today. Use it from your connected AI after setup.
No other account needed.
Connect ahel once, and every AI you use reads what you have installed.
Then ask your AI: use the MongoDB Data-Access Rules skill
What this skill tells your AI
The instructions your AI receives, as published by thedecipherist/claude-code-mastery-project-starter-kit in .claude/skills/mongodb-rules/SKILL.md and read by ahel’s review.
Non-negotiable for this codebase. From production, not preference.
Driver and connection
- Prefer StrictDB; fall back to the native driver. Use StrictDB when it's installed, otherwise the native MongoDB driver directly. Never Mongoose, either way.
- Data access stays in the adapter, never raw collections scattered through feature code.
- One shared
MongoClientfor the whole app, created once at startup and reused everywhere. The client is the pool. Never create one per request, that exhausts connections and looks like "MongoDB went down" under load. In serverless, declare the client at module scope, outside the handler, so warm invocations reuse it. - URI comes from an env var, never hardcoded. Close the client on
SIGTERM/SIGINT.
Identity and types
_idis anObjectId, not a string. A string_idagainst anObjectIddocument matches nothing, silently. This is the number-one "my id query returns nothing" bug. Wrap incoming ids withnew ObjectId(id); for an$inlist, convert every element.- Never put
_idin the body of any write. Identity goes in the filter; on insert MongoDB generates it. Restating it after a JSON round-trip throws code 66 (immutable field altered). - JSON strips both
ObjectIdandDateto strings. Re-hydrate at the boundary before you query or save, or lookups match nothing and date filters break. Use a parse-time reviver (parseMongo) or a bounded post-parse walk (rehydrateTypes,maxDepth=3). Never patch the globalJSON.parse. Guard withObjectId.isValidand askipKeyslist. - Consider a natural string
_id(email, SKU, slug) to sidestep the type dance entirely, then ids are strings end to end. - Only
_idis indexed by default. Sorting by_idgives roughly creation order for free, but store an explicitcreatedAtwhen creation time matters; don't rely on the ObjectId's embedded timestamp.
Querying
nullis not "missing".{ field: null }matches both explicit null AND absent documents. Use{ field: { $exists: false } }for missing, and{ field: { $ne: null } }for "has a real value" (which excludes both null and missing).- Reads are aggregation pipelines, not
find(). - Arrays-within-arrays aren't queryable past about three levels (
maxDepth=3). If you need to, the model is wrong, flatten it.
Writes
- Multi-document writes use
bulkWrite. Build the ops array in the loop, execute onebulkWriteafter it. Never call the database inside a loop. - Choose ordered vs unordered deliberately.
ordered(default) stops at the first error;{ ordered: false }attempts all and collects errors, and is faster. On partial failure, triage transient vs permanent: retry only transient ops with backoff, never blind-retry a duplicate-key or validation failure. - Make writes idempotent (stable keys, set-to-value over blind increments) so retry is safe.
- Upsert is
updateOnewithupsert: true. Use$setOnInsertfor insert-only fields, and pair it with a unique index so concurrent upserts can't duplicate.
Indexing
createIndexis idempotent but not free, each call is a round trip. Declare indexes near the queries that need them, but create them once in startup or a migration, never in a handler or hot loop.- A compound index serves only a left-to-right prefix of its fields. Order fields to match how you query; equality-matched fields lead.
- For filter-plus-sort, follow ESR: Equality, Sort, Range. Index direction must match the sort or be its exact inverse. An in-memory
SORTstage inexplainmeans the index isn't serving the sort. - Filter early (
$matchfirst), and put$limitbefore$lookup. Diagnose withexplain("executionStats"): examined far exceeding returned means a missing index.
Modeling
- Embed bounded, read-together data; reference unbounded data (comments, events, logs, anything that accumulates). A document is rewritten and moved as a whole, so an unbounded array degrades writes long before the 16MB hard limit.
$elemMatchusually signals a modeling problem. A field you query independently belongs on the document or in its own collection.
Concurrency and integrity
- MongoDB has full ACID transactions, but a single-document write is already atomic. Reach for
session.withTransactiononly for genuine cross-document atomicity (transfer between accounts, decrement stock while creating an order). Frequent transactions are a modeling smell, the data probably wanted to be one document. - Unique values are enforced by a unique index, not app-level checks. Use a partial unique index for optional fields (a plain unique index treats missing as null and collides). Use a compound unique index for "this combination is unique". The duplicate-key error is the guarantee that makes concurrent upserts safe.
Reads at scale
- Counting is a choice.
countDocumentsis exact (index the filter to keep it fast);estimatedDocumentCountis instant but approximate and whole-collection only, use it for rough dashboard totals.distincton a high-cardinality field at scale should be a$groupso the result streams. $skipdoesn't scale, it walks past every skipped document. For deep or endless paging, use range/keyset pagination:$matchon the last-seen value of an indexed sort key, with_idas a unique tie-breaker so pages don't shift as data changes.
Schema
Collections enforce no structure by default, so validate in two layers.
- Parse before every write. Validate each document against its Zod schema right before it hits the database, so a malformed shape never lands. The schema itself isn't Mongo-specific, it's the same contract the API and frontend use, see the
schema-source-of-truthskill for defining it once and deriving every layer from one base. - Keep a
$jsonSchemacollection validator as the floor. Zod only guards writes that go through your app, so the DB validator is the last line that also catches mongosh, scripts, and other services. Add it as a collection stabilizes and more code depends on its shape. Roll out safely:validationAction: "warn"to observe first, thenerror;validationLevel: "moderate"to spare existing nonconforming documents.
Signals
- GitHub stars
- 338
- Forks
- 40
- Last commit
- Jun 2026
ahel review
S4info
community integration — published by thedecipherist, not mongodb
Automated review, not a security audit. Ruleset v1+k2.
Advanced
- Catalog kind
- skill
- Gateway key
mongodb-rules- Source
- github.com/thedecipherist/claude-code-mastery-project-starter-kit