Generated banner for Mongodb Schema Design
Generated logo for Mongodb Schema Design

Mongodb Schema Design

MongoDBOfficialPublished by MongoDB

  • Skill
  • Guidelines
  • Data and AI
  • Apache-2.0
  • No issues found

From the author

MongoDB schema design patterns and anti-patterns. Use when designing data models, reviewing schemas, migrating from SQL, or troubleshooting performance issues caused by schema problems. Triggers on "design schema", "embed vs reference", "MongoDB data model", "schema review", "unbounded arrays", "one-to-many", "tree structure", "16MB limit", "schema validation", "JSON Schema", "time series", "schema migration", "polymorphic", "TTL", "data lifecycle", "archive", "index explosion", "unnecessary indexes", "approximation pattern", "document versioning".
— the description by MongoDB

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a comprehensive framework for designing, reviewing, and optimizing MongoDB data models. It emphasizes the core philosophy that data accessed together should be stored together, offering actionable patterns for embedding versus referencing, handling time-series data, and avoiding common pitfalls like unbounded arrays or excessive collection splitting. It includes diagnostic workflows to analyze access patterns and performance, ensuring schema decisions are driven by real-world workload requirements rather than theoretical assumptions.

What it does

  • Provides patterns for common modeling challenges like tree structures, polymorphic data, and time-series.
  • Identifies anti-patterns such as unnecessary collections, excessive lookups, and index bloat.
  • Offers a decision framework for choosing between embedding and referencing based on access patterns.
  • Guides users through performance analysis using query statistics and slow query logs.
  • Includes best practices for schema validation and managing document size limits.
  • Supports integration with MongoDB MCP for automated schema verification and diagnostic tasks.

When to use it

  • When designing a new MongoDB data model from scratch.
  • When migrating existing data from a relational SQL database to MongoDB.
  • When troubleshooting performance issues like slow queries or high index overhead.
  • When documents are hitting the 16MB size limit or exhibiting inconsistent structures.
  • When evaluating whether to denormalize data or use $lookup operations.

Advantages

  • Reduces performance bottlenecks by aligning schema design with actual application access patterns.
  • Prevents common pitfalls that lead to high storage costs and inefficient query execution.
  • Provides a structured, evidence-based approach to schema evolution and migration.
  • Enables data-driven decision making by combining design patterns with real-time diagnostic data.

Usage examples

“How should I model a one-to-many relationship between users and their orders?”
The agent will analyze your access patterns to determine if you should embed the orders within the user document or store them in a separate collection, based on the frequency of access and document size.
“My queries are slow and I see a lot of $lookup stages in my logs. How can I fix this?”
The agent will guide you through identifying if your data is over-normalized and suggest specific denormalization or embedding strategies to reduce join overhead.
“I am migrating from SQL to MongoDB. How do I handle my normalized tables?”
The agent will help you identify tables that are frequently joined and demonstrate how to merge them into rich, denormalized documents for better performance.
“How can I prevent my documents from growing indefinitely?”
The agent will explain patterns like the bucket pattern or archiving to manage unbounded data and ensure your documents stay within the 16MB limit.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/mongodb/mongodb-schema-design/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip mongodb-schema-design.zip -d .agents/skills

Documentation by MongoDB

MongoDB Schema Design

Data modeling patterns and anti-patterns for MongoDB, maintained by MongoDB. Bad schema is the root cause of most MongoDB performance and cost issues—queries and indexes cannot fix a fundamentally wrong model.

When to Apply

Reference these guidelines when:

  • Designing a new MongoDB schema from scratch

  • Migrating from SQL/relational databases to MongoDB

  • Reviewing existing data models for performance issues

  • Troubleshooting slow queries or growing document sizes

  • Deciding between embedding and referencing

  • Modeling relationships (one-to-one, one-to-many, many-to-many)

  • Implementing tree/hierarchical structures

  • Seeing Atlas Schema Suggestions or Performance Advisor warnings

  • Hitting the 16MB document limit

  • Adding schema validation to existing collections

Quick Reference

1. Schema Anti-Patterns - 3 rules
  • antipattern-unnecessary-collections - Splitting homogeneous data into multiple collections is often an anti-pattern; consult this reference to validate whether this is the case.

  • antipattern-excessive-lookups - When encountering overly normalized collections that reference each other or frequent and possibly slow $lookup operations, consult this reference to validate whether this is problematic and how to fix it.

  • antipattern-unnecessary-indexes - Consult this reference when indexes overlap or are not used by queries, to identify and remove unnecessary indexes that add overhead without benefit.

2. Schema Fundamentals - 4 rules
  • fundamental-embed-vs-reference - Consult this reference for approaches to modeling different types of relationships (1:1, 1:few, 1:many, many:many, tree/hierarchical data) and how to decide between embedding and referencing based on access patterns.

  • fundamental-document-model - Fundamentals of the document model. Consult this reference when migrating from SQL or other normalized data to a document database like MongoDB.

  • fundamental-schema-validation - Consult this reference when creating new collections, or adding validation to existing collections, for example in response to finding inconsistent document structures or data quality issues.

  • fundamental-document-size - Consult this reference when documents hit the hard 16MB limit, or when accesses are slower than expected as a result of large documents.

3. Design Patterns - 11 rules
  • pattern-approximation - Use approximate values for high-frequency counters

  • pattern-archive - Move historical data to separate/cold storage for performance

  • pattern-attribute - Collapse many optional fields into key-value attributes

  • pattern-bucket - Group time-series or IoT data into buckets

  • pattern-computed - Pre-calculate expensive aggregations

  • pattern-document-versioning - Track document changes to enable historical queries and audit trails

  • pattern-extended-reference - Cache frequently-accessed data from related entities

  • pattern-outlier - Handle collections in which a small subset of documents are much larger than the rest, to prevent outliers from dominating memory and index costs

  • pattern-polymorphic - Store different types of entities in the same collection, often when they are different types of the same base entity (e.g. different types of users or different types of products)

  • pattern-schema-versioning - Schema evolution, preventing drift, and safe online migrations. Consult when encountering inconsistent document structures, or when planning a schema change that cannot be applied atomically.

  • pattern-time-series-collections - Use native time series collections for high-frequency time series data

Access Pattern Analysis

Do not immediately recommend a pattern or schema change without understanding the broader context. Together with the user, analyze access patterns to identify pain points and opportunities for optimization.

Workflow

Step 1: Assess the environment Ask the user:

  • Is this a new design or is there a production database with existing access patterns to analyze?

  • If there is production data, is it on Atlas? If yes, what tier? (M0/M2/M5 vs M10+)

Step 2: Determine workload type Is the workload read-heavy, write-heavy, or balanced? This will influence which diagnostic sources are most relevant. Ask the user:

  • What's the primary workload for these collections — read-heavy (analytics, reports, searches), write-heavy (logging, IoT ingestion, frequent updates), or balanced?

Verify with db.serverStatus().opcounters.

Step 3: Work with the user to choose the best source(s) Recommend the best source(s) for their situation, explaining the tradeoffs. For schema design decisions, we often need to combine multiple sources for a complete picture.

Step 4: Proceed with analysis Only after source selection, fetch data or guide the user through analysis.

Sources
  • Query statistics - Returns runtime statistics for recorded queries showing query shapes and frequency. Limitation: Currently only captures read operations (pair with other sources for write patterns). Requires Atlas M10+ tier.

  • Atlas Slow Query Logs - Review slow queries (actual queries, not shapes) to identify performance bottlenecks. Captures all reads and writes. Requires Atlas M10+ tier.

  • Codebase - Examine actual queries in application code to understand access patterns, especially for new applications or with changing workloads. Can be used in conjunction with query stats for a more complete picture.

  • Natural language input - Ask the user to describe their typical queries and access patterns in natural language. Can be used as the only source or to supplement and validate other sources - the user might have contextual knowledge that is not reflected in the data or codebase.

Combining Query Stats and Slow Query Logs:

Use both together for comprehensive analysis:

  1. Query Stats → identify frequent access patterns (which queries run most often)

  2. Slow Query Logs → identify performance bottlenecks (which queries are slow)

  3. Focus schema optimization on queries that are both frequent AND slow (highest impact)

Key Principle

"Data that is accessed together should be stored together."

This is MongoDB's core philosophy. Embedding related data eliminates joins, reduces round trips, and enables atomic updates. Reference only when you must.

A core way to implement this philosophy is the fact that MongoDB exposes flexible schemas. This means you can have different fields in different documents, and even different structures. This allows you to model data in the way that best fits your access patterns, without being constrained by a rigid schema. For example, if different documents have different sets of fields, that is perfectly fine as long as it serves your application's needs. You can also use schema validation to enforce certain rules while still allowing for flexibility.

Another implication of the key principle is that information about the expected read and write workload becomes very relevant to schema design. If pieces of information from different entities are often queried or updated together, that means that prioritizing co-location of that data in the same document can lead to significant performance benefits. On the other hand, if certain pieces of information are rarely accessed together, it may make sense to store them separately to avoid loading more data than necessary.

Schema Fundamentals Summary
  • Embed vs Reference: Choose embedding or referencing based on access patterns: embed when data is always accessed together (1:1, 1:few, bounded arrays, atomic updates needed); reference when data is accessed independently, relationships are many-to-many, or arrays can grow without bound.

  • Data accessed together stored together: MongoDB's core principle: design schemas around queries, not entities. Embed related data to eliminate cross-collection joins and reduce round trips. Identify your API endpoints/pages, list the data each returns, then shape documents to match those queries.

  • Embrace the document model: Don't recreate SQL tables 1:1 as MongoDB collections. Instead, denormalize joined tables into rich documents for single-query reads and atomic updates. When migrating from SQL, identify tables that are always joined together and merge them into single documents.

  • Schema validation: Use MongoDB's built-in $jsonSchema validator to catch invalid data at the database level (type checks, required fields, enum constraints, array size limits). Start with validationLevel: "moderate" and validationAction: "warn" on existing collections, then tighten to strict/error.

  • 16MB document limit: MongoDB documents cannot exceed 16MB—this is a hard limit, not a guideline. Common causes: unbounded arrays, large embedded binaries, deeply nested objects. Mitigate by moving unbounded data to separate collections and monitoring document sizes with $bsonSize.

Embed/Reference Decision Framework

RelationshipCardinalityAccess PatternRecommendation
One-to-One1:1Always togetherEmbed
One-to-Few1:N (N < 100)Usually togetherEmbed array
One-to-Many1:N (N > 100)Often separateReference
Many-to-ManyM:NVariesTwo-way reference

This is a rough guideline, and whether to embed or reference depends on your specific access patterns, data size, and read/write frequencies. Always verify with your actual workload.

How to Use

Each reference file listed above contains detailed explanations and code examples. Use the descriptions in the Quick Reference to identify which files are relevant to your current task.

Each reference file contains:

  • Brief explanation of why it matters

  • Incorrect code example with explanation

  • Correct code example with explanation

  • "When NOT to use" exceptions

  • Performance impact and metrics

  • Verification diagnostics


How These Rules Work

MongoDB MCP Integration

For automatic verification, connect the MongoDB MCP Server.

If the MCP server is running and connected, I can automatically run verification commands to check your actual schema, document sizes, array lengths, index usage, slow query logs, and more. This allows me to provide tailored recommendations based on your real data, not just code patterns.

⚠️ Security: Use --readOnly for safety. Remove only if you need write operations.

When connected, I can automatically:

  • Infer schema via mcp__mongodb__collection-schema

  • Measure document/array sizes via mcp__mongodb__aggregate

  • Check collection statistics via mcp__mongodb__db-stats

⚠️ Action Policy

I will NEVER execute write operations without your explicit approval.

Before any write or destructive operation via MCP, I will: (1) summarize the exact operation (collection, index/validator, estimated number of docs affected), and (2) ask for explicit confirmation (yes/no). I will not proceed on partial or ambiguous approvals.

Operation TypeMCP ToolsAction
Read (Safe)find, aggregate, collection-schema, db-stats, countI may run automatically to verify
Write (Requires Approval)update-many, insert-many, create-collectionI will show the command and wait for your "yes"
Destructive (Requires Approval)delete-many, drop-collection, drop-databaseI will warn you and require explicit confirmation

When I recommend schema changes or data modifications:

  1. I'll explain what I want to do and why

  2. I'll show you the exact command

  3. I'll wait for your approval before executing

  4. If you say "go ahead" or "yes", only then will I run it

Your database, your decision. I'm here to advise, not to act unilaterally.

Working Together

If you're not sure about a recommendation:

  1. Run the verification commands I provide

  2. Share the output with me

  3. I'll adjust my recommendation based on your actual data

We're a team—let's get this right together.

Files

LICENSE

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
MongoDB
Publisher
MongoDB (Official)
Source
mongodb/agent-skills · skills/mongodb-schema-design · commit 155bb9c
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Also distributed in
mongodb/agent-skills, mongodb/agent-skills

AutoGineer is not affiliated with or endorsed by MongoDB or MongoDB.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download mongodb-schema-design.zip