MongoDB Expert Knowledge
MongoDB Expert
This local skill is generated from docs/mongodb-expert-context.md in 10gen/mdb-tam.
This skill consolidates 24 MongoDB data-plane/engine sub-skills as on-demand reference files under references/. It is the primary, first-choice skill for core MongoDB questions — not a fallback. Match the task to the Sub-skill routing table below and Read the listed references/…md file before answering deep questions — the table alone is not enough for depth. Route to a sibling hub (mongodb-atlas-expert, atlas-diagnostics-expert, mongodb-operations-expert, mongodb-kb) only when the question falls into one of those domains (see frontmatter SKIP).
When to use this skill
Use this skill when the user needs help with core MongoDB data-plane or database-engine topics. Start from the bundled context below for fundamentals, load the relevant references/ file for depth, and defer to the cited official documentation for exact APIs, commands, and edge-case behavior.
Sub-skill routing table
This hub absorbs 24 former standalone skills as on-demand reference files. When a task matches a row, Read the listed references/ file before answering — do not rely on this table alone for depth. For domains not listed here (Atlas cloud platform, live diagnostics, ops/backup/migration/security, KB lookup), route to the sibling hub named in the frontmatter SKIP line.
| Sub-topic | When to load | Reference file |
|---|---|---|
mongodb-developer |
Driver usage across all official drivers (Node.js, Python, Java, Go, C#, Rust, …) — connection pooling, transactions, bulk ops, GridFS | references/mongodb-developer.md |
mongodb-aggregation-pipeline |
Aggregation pipeline fundamentals — stage order, operators, materialization | references/mongodb-aggregation-pipeline.md |
mongodb-aggregation-stages-deep |
Deep aggregation stages — $lookup, $graphLookup, $facet, $bucket/$bucketAuto, $merge/$out, $setWindowFields, $densify/$fill, $unionWith |
references/mongodb-aggregation-stages-deep.md |
mongodb-indexes-deep |
Every index type — single-field, compound, multikey, partial, wildcard, hidden, TTL, hashed | references/mongodb-indexes-deep.md |
mongodb-query-performance |
Query optimization, explain plans, ESR rule, slow-query diagnosis, index hints | references/mongodb-query-performance.md |
mongodb-schema-design |
Embedding vs referencing trade-offs, 12 canonical design patterns, tree structures, validation | references/mongodb-schema-design.md |
mongodb-transactions |
Multi-document transactions — replica-set and sharded, callback API, retry, read/write concerns | references/mongodb-transactions.md |
mongodb-change-streams |
Change streams — oplog architecture, resume tokens, pre/post images, split events | references/mongodb-change-streams.md |
mongodb-time-series |
Time-series collections — timeField/metaField, granularity, bucketing, TTL, downsampling |
references/mongodb-time-series.md |
mongodb-geospatial |
Geospatial queries, indexes, and data model — 2dsphere, GeoJSON, near/within, polygons | references/mongodb-geospatial.md |
mongodb-views-materialized-views |
Standard read-only views and on-demand $merge-backed materialized views |
references/mongodb-views-materialized-views.md |
mongodb-bson-types |
BSON type system — type table with codes/aliases, comparison order, edge cases | references/mongodb-bson-types.md |
mongodb-error-codes |
Numeric server error codes and correct driver retry behavior | references/mongodb-error-codes.md |
mongodb-connection-string |
Connection-string URI formats and options — SRV, TLS, authSource, appName | references/mongodb-connection-string.md |
mongodb-driver-internals |
Driver internals — CMAP connection pooling, SDAM, server selection, retryable writes, OCSP | references/mongodb-driver-internals.md |
mongodb-drivers-k8s |
Driver patterns plus Kubernetes operator — connection management, transactions, change streams, retry | references/mongodb-drivers-k8s.md |
mongodb-wiredtiger |
WiredTiger internals, cache tuning, eviction mechanics, checkpoint behavior | references/mongodb-wiredtiger.md |
mongodb-wiredtiger-internals |
WiredTiger deep internals — cache, checkpointing, MVCC, eviction, snapshot reads | references/mongodb-wiredtiger-internals.md |
mongodb-mongosh |
mongosh shell — methods, scripts, snippets, db.* admin commands |
references/mongodb-mongosh.md |
mongodb-database-tools |
Database tools — mongodump, mongorestore, mongoimport, mongoexport, archive/BSON streaming | references/mongodb-database-tools.md |
mongodb-multi-tenancy |
Multi-tenancy data layout — tenant-per-DB, tenant-per-collection, shared collection | references/mongodb-multi-tenancy.md |
mongodb-sharding |
Sharding architecture, shard-key selection (ranged, hashed, compound), balancer, zones, resharding | references/mongodb-sharding.md |
mongodb-replication |
Replica-set architecture — primaries/secondaries/arbiters/hidden/delayed, elections, oplog, failover | references/mongodb-replication.md |
mongodb-compass |
Compass GUI — query builder, schema analysis, performance tab | references/mongodb-compass.md |
Cross-hub routing (domains this hub does NOT own)
The Sub-skill routing table above is the authoritative map of the 24 reference files this hub owns — always route data-plane/engine depth through references/<name>.md, never to a standalone skill name (those skills no longer exist).
For domains outside this hub, route to the sibling hub that owns them. Each sibling hub has its own internal routing table for its sub-areas — do not name individual sub-skills here:
| Domain area | Route to sibling hub |
|---|---|
| Atlas cloud platform / control plane — orgs, projects, deployments, Admin API, Atlas CLI, Terraform, Kubernetes Operator (AKO), tiers, IAM/RBAC, federated auth, service accounts, Atlas Search / $search, Vector Search / $vectorSearch, Search Nodes, Stream Processing, Charts, Data Federation, Online Archive, App Services, Triggers/Functions, Device SDK / Realm sync, BI Connector, analytics nodes, global clusters, Flex/Serverless, multicloud + AWS/Azure/GCP networking | mongodb-atlas-expert |
| Live cluster diagnostics, performance troubleshooting, benchmarking, monitoring/observability, capacity planning | atlas-diagnostics-expert |
| Backup/restore, disaster recovery, Ops Manager, migration (mongosync, Relational Migrator, Live Migration, cutover), upgrade paths, security architecture, encryption (CSFLE/Queryable Encryption), compliance, cost optimization, Kafka/Spark connectors, CDC architecture | mongodb-operations-expert |
| KB / troubleshooting article lookup | mongodb-kb |
| Install / run MongoDB locally from a repo | 10gen |
| Generic schema/data-migration patterns (expand-contract, backfill, zero-downtime) | database-migrations |
When a question crosses categories, pick the deepest reference that covers the primary concern, load it, then cross-link to the relevant sibling hub for the secondary concern.
Skill guidance
- Treat
docs/mongodb-expert-context.mdas the source document for this skill. - Prefer the workflows, checklists, and constraints captured in the bundled context before improvising.
- If the request is outside this topic, choose a more appropriate skill instead of forcing this one.
- For deep data-plane/engine questions, Read the matching
references/<name>.mdfile from the Sub-skill routing table rather than improvising from this overview. For out-of-domain questions, route to the sibling hub named in the cross-hub routing table above.
Bundled context
Source: docs/mongodb-expert-context.md in the mdb-tam repository.
MongoDB expert context
How to use this context
Use this file as a practical MongoDB reference when designing schemas, writing queries, reviewing data-access code, or debugging performance issues. Treat the MongoDB Manual and driver docs as the primary operational/application references, and use the MQL, operator, command, and method reference pages for exact behavior and syntax details (MongoDB Manual, MongoDB Drivers, MQL reference, mongosh methods).
Source scope
- Platform overview: MongoDB docs home and Manual (MongoDB docs, MongoDB Manual).
- Application-facing usage: official MongoDB driver docs (MongoDB Drivers).
- Exact language behavior: MongoDB Query Language reference, CRUD command reference, query predicate operators, update operators, projection operators, aggregation docs, and aggregation operator reference (MQL reference, CRUD commands, Query operators, Update operators, Projection operators, Aggregation, Aggregation operators).
- Shell-specific usage: mongosh method reference (mongosh methods).
- Design and performance guidance: data modeling, indexes, write atomicity, and transactions docs (Data modeling, Indexes, Write atomicity, Transactions).
- These sources are MongoDB-specific references and practices, not a general application architecture style guide. Where they do not prescribe naming, repository structure, or language-specific code style, defer to project-local conventions (MongoDB Manual, MongoDB Drivers).
Quick rules
- Model data around access patterns; data accessed together should generally be stored together (Data modeling).
- Prefer embedding when it lets you satisfy common reads in a single-document fetch; MongoDB explicitly highlights document structures as a way to avoid unnecessary multi-document transactions (Data modeling, Transactions).
- Remember that write operations are atomic at the single-document level, but multi-document operations are not atomic as a whole unless you use transactions (CRUD, Write atomicity, Transactions).
- Create indexes for repeatedly queried fields, but remember every index has a write cost (Indexes).
- Prefer aggregation pipelines for aggregations; MongoDB calls them the preferred aggregation method (Aggregation).
- Use the driver in applications; the MongoDB docs explicitly note that most interactions use an idiomatic driver rather than JavaScript shell methods (mongosh methods, MongoDB Drivers).
- When concurrent updates matter, include the expected current value in the filter or use operators like
$incto avoid accidental lost updates (Write atomicity). - Use transactions only when you truly need multi-document atomicity; many use cases can be modeled to avoid them (Transactions, Data modeling).
- Treat MQL as more than simple find filters: it includes query predicates, projections, updates, expressions, and aggregation stages/operators (MQL reference).
- Separate driver usage from mongosh usage in your mental model; shell methods are reference and tooling conveniences, not the main application API surface (mongosh methods, MongoDB Drivers).
Core MongoDB model
Document model and collections
- MongoDB is a document-oriented operational database that stores rich JSON-like documents which map naturally to application objects (MongoDB docs).
- The document data model is flexible: documents in the same collection do not need identical fields, and a field’s type can differ between documents in the same collection (MongoDB Manual, Data modeling).
- Collections group documents; insert operations target a single collection and create it if it does not exist (CRUD).
MQL and how to think about it
- MongoDB Query Language (MQL) includes query predicates, aggregation pipelines, expressions, projections, accumulators, update operators, and CRUD commands (MQL reference).
- Query predicates are boolean expressions that determine whether a document matches a query (Query operators).
- Aggregation expressions are stateless and resolve to a value without mutating their inputs (Aggregation operators).
CRUD and write semantics
CRUD basics
- CRUD covers create, read, update, and delete of documents (CRUD).
- MongoDB provides collection-level methods such as
insertOne()andinsertMany()for insert operations (CRUD). - At the command layer, CRUD includes commands such as
find,insert,update,delete,distinct,aggregate,findAndModify,count, andbulkWrite(CRUD commands).
Atomicity and concurrent updates
- All write operations are atomic at the single-document level, even if they modify multiple values inside that document (CRUD, Write atomicity).
- A multi-document update operation modifies each individual document atomically, but the operation as a whole is not atomic (Write atomicity).
- To avoid conflicts in concurrent updates, include the expected current value in the update filter; filtering only by
_idwhile setting a value can cause the second update to overwrite the first silently (Write atomicity). $incis specifically called out as a safer concurrent pattern than naive overwrite-based$setin some conflict scenarios (Write atomicity).
Transactions
- Single-document operations are atomic, and MongoDB explicitly notes that embedded documents and arrays often remove the need for multi-document transactions (Transactions).
- MongoDB supports transactions across multiple operations, collections, databases, documents, and shards when true multi-document atomicity is required (Transactions).
- The callback transaction API starts a transaction, executes operations, and commits or ends it on error; it also incorporates retry logic for some errors such as
TransientTransactionErrorandUnknownTransactionCommitResult(Transactions). - There are version-sensitive transaction caveats, including explicit notes in the docs about changed retry behavior in newer server versions (Transactions).
Data modeling and schema design guidance
Core design principle
- A core MongoDB modeling principle is that data accessed together should be stored together (Data modeling).
- Structure the model according to actual application data access patterns to optimize performance (Data modeling).
Embedding vs referencing
- MongoDB’s examples explicitly favor embedding when related data is commonly returned together in a single query, such as department info embedded in employee records (Data modeling).
- Referencing or separating collections makes sense when some related data is accessed much less frequently, such as older product reviews stored separately from the hot product-page subset (Data modeling).
- Because documents can be polymorphic, a single collection can support differently shaped items when that matches the application’s model (Data modeling).
Indexes and performance
- Indexes allow MongoDB to avoid scanning every document in a collection for supported queries (Indexes).
- Without an appropriate index, MongoDB must scan every document to return results (Indexes).
- Indexes improve read/query performance but add negative performance impact to writes because inserts and updates must also maintain indexes (Indexes).
- If your application repeatedly runs queries on the same fields, MongoDB explicitly recommends creating indexes on those fields (Indexes).
Aggregation
- Aggregation processes multiple documents and returns computed results, including grouping values, analyzing changes over time, and querying the latest form of data (Aggregation).
- MongoDB calls aggregation pipelines the preferred aggregation method (Aggregation).
- A pipeline is made of one or more stages, each of which transforms or filters documents before passing them to the next stage (Aggregation).
- Aggregation expressions can be used in stages like
$project,$addFields, and$group, in$exprpredicates, and in projections (Aggregation operators).
Driver vs mongosh guidance
- Most real application interaction with MongoDB uses an idiomatic driver, not JavaScript shell methods (mongosh methods, MongoDB Drivers).
- The mongosh method reference is specifically about shell methods and notes that these are functional replacements for legacy shell APIs, not exact replacements in every detail (mongosh methods).
- Application code should primarily think in terms of the official driver for its language/runtime, while keeping the shell reference available for exploration, debugging, and administrative workflows (MongoDB Drivers, mongosh methods).
Methods, operators, and APIs inventory
This is a condensed high-value inventory, not a verbatim dump of every MongoDB operator or method.
CRUD methods and commands
| API | Purpose | Key args/params | Return/effect | Typical usage | Caveats |
|---|---|---|---|---|---|
db.collection.insertOne() |
Insert one document (CRUD) | document | Adds one document to a collection | Single-document creation | Targets one collection; creates collection if needed |
db.collection.insertMany() |
Insert multiple documents (CRUD) | array of documents | Adds many documents | Batch creation | Still collection-scoped |
find command / db.collection.find() |
Select documents from a collection or view (CRUD commands) | query filter, projection, options | Returns matching documents/cursor semantics depending API | Reads by predicate | Behavior differs slightly by driver/shell surface |
update command / update methods |
Update one or more documents (CRUD commands) | filter, update document/operators, options | Modifies matched docs | Targeted updates | Single-doc atomicity only |
delete command / delete methods |
Delete one or more documents (CRUD commands) | filter | Removes matched docs | Cleanup or lifecycle deletion | Multi-doc deletions are not atomic as a whole |
findAndModify |
Modify and return a single document (CRUD commands) | filter, modification, options | Returns/modifies one document | Read-modify-write workflows | Single-document oriented |
aggregate |
Run aggregation pipeline on collection or view (CRUD commands, Aggregation) | pipeline stages, options | Computed result set | Analytics, reshaping, derived results | Prefer pipelines over older/simpler aggregation approaches |
distinct |
Return distinct values for a field (CRUD commands) | field, filter/options | Unique values | Faceting-style retrieval | Index support matters for performance |
bulkWrite |
Perform many write ops in one request (CRUD commands) | batched operations | Many inserts/updates/deletes | High-throughput batch write workflows | Command-level semantics are version-sensitive; docs note it is new in 8.0 |
Query, projection, and update operators
| API | Purpose | Key args/params | Return/effect | Typical usage | Caveats |
|---|---|---|---|---|---|
| Query predicates | Boolean document matching expressions (Query operators) | field/operator/value expressions | Match or reject documents | Filtering in reads and updates | Operator category matters: array, comparison, logical, geospatial, etc. |
$eq and other comparison operators |
Compare field values in predicates (Query operators) | field comparisons | Match docs by comparison | Standard filtered reads | Use the right operator family for the predicate |
$expr |
Use expressions inside query predicates (Aggregation operators) | expression tree | Boolean match behavior in query context | Computed predicate logic | Pulls expression semantics into query matching |
$ projection operator |
Project first array element matching query condition (Projection operators) | projection syntax | Limits returned array content | Array-focused reads | Not supported on view find() operations |
$elemMatch projection |
Project first array element matching explicit condition (Projection operators) | $elemMatch projection condition |
Limits returned array content | Focused array projections | Not supported on view find() operations |
$slice projection |
Limit number of projected array elements (Projection operators) | skip/limit slice args | Returns subset of array | Smaller array payloads | Not supported on view find() operations |
$set |
Set field value in document (Update operators) | field/value map | Overwrites target field values | Standard updates | Can clobber concurrent overwrite-based updates |
$inc |
Increment numeric field by amount (Update operators, Write atomicity) | field/amount map | Adds delta | Counters, safer concurrent increments | Preferred in some concurrent update scenarios |
$currentDate |
Set field to current date or timestamp (Update operators) | field spec | Writes current temporal value | Updated-at style fields | Field ordering behavior is version-sensitive |
$setOnInsert |
Set field only on upsert-insert path (Update operators) | field/value map | Applies only when upsert inserts | Default values on upsert | No effect on plain matched update |
Aggregation building blocks
| API | Purpose | Key args/params | Return/effect | Typical usage | Caveats |
|---|---|---|---|---|---|
| Aggregation pipeline | Preferred aggregation flow (Aggregation) | ordered list of stages | Transforms/aggregates documents | Reporting, reshaping, analytics | Stage order matters |
$project |
Reshape/project fields (Aggregation operators) | projection expression | New document shape | Output shaping | Expression-driven, stateless logic |
$addFields |
Add computed fields (Aggregation operators) | field/expression mapping | Augmented document | Derived values mid-pipeline | Watch pipeline complexity |
$group |
Group documents and compute accumulated values (Aggregation, Aggregation operators) | grouping key plus accumulators | Grouped aggregate output | Rollups and metrics | Requires accumulator semantics |
Expressions such as $add |
Compute values from constants, operators, and field paths (Aggregation operators) | operator plus operands | Value result | Arithmetic, transforms, computed projections | Expressions are stateless |
Coding standards and best practices from the docs
Schema and data modeling
- Design schemas from application access patterns, not from generic normalization habits alone (Data modeling).
- Use the flexible document model intentionally; polymorphic collections are valid when they match application needs (Data modeling).
Collection design
- Keep data that is accessed together together, often in the same document (Data modeling).
- Use separate collections when data is colder or accessed on a different cadence than the hot path (Data modeling).
Embedding vs referencing
- Prefer embedding for closely related, co-read data (Data modeling).
- Prefer referencing/separation when data has different access frequency or lifecycle characteristics (Data modeling).
Query design
- Understand the operator category you need: comparison, logical, array, data type, and specialized predicate families are distinct tools (Query operators).
- Use projections deliberately to reduce payload and focus reads, especially for arrays and metadata-heavy results (Projection operators).
Index strategy
- Add indexes for repeated query patterns, but account for the write cost of each index (Indexes).
- Use indexes to avoid unnecessary collection scans; lack of a supporting index forces broader scans (Indexes).
Aggregation usage
- Prefer aggregation pipelines over older or more limited aggregation mechanisms (Aggregation).
- Keep pipeline stages purposeful and ordered to progressively narrow, enrich, or reshape data (Aggregation).
Update patterns
- Prefer update filters that encode expected current state in concurrent workflows (Write atomicity).
- Use arithmetic or intent-specific operators like
$incinstead of read-modify-overwrite patterns when concurrency matters (Write atomicity, Update operators).
Transaction usage
- Do not default to transactions for everything; MongoDB explicitly notes many practical use cases can avoid them through document design (Transactions).
- Use transactions when you genuinely need multi-document, multi-collection, or cross-shard atomicity (Transactions).
Driver usage vs shell usage
- In application code, prefer the official driver for the language/runtime you are using (MongoDB Drivers).
- Treat mongosh methods as shell/documentation/admin tooling, not as the main application API model (mongosh methods).
Maintainability and performance
- Favor data layouts that satisfy common reads efficiently and avoid unnecessary joins/workarounds in application code (Data modeling).
- Balance read optimization with write costs when designing indexes and update patterns (Indexes, Write atomicity).
Practical defaults for future coding tasks
- Start schema design by listing the most important read and write paths, then shape documents around them (Data modeling).
- Start performance work by checking query/index fit before reaching for broader architectural changes (Indexes).
- Prefer driver-level APIs in production code and keep shell snippets clearly separated as examples or admin workflows (MongoDB Drivers, mongosh methods).
- Prefer single-document designs and single-document atomic operations where possible; add transactions only when requirements genuinely cross document boundaries (Write atomicity, Transactions).
Known ambiguities / version-sensitive notes
- The MongoDB docs site is a living docs system; exact behavior can vary by server version, driver version, and API surface, so record the relevant version when precision matters (MongoDB docs, MongoDB Drivers).
- Some command and transaction behaviors are explicitly version-sensitive in the docs, such as
bulkWritebeing marked new in 8.0 and transaction retry caveats changing in newer versions (CRUD commands, Transactions). - The mongosh method reference is not a universal application API reference; it is shell-specific and explicitly distinguished from idiomatic driver usage (mongosh methods, MongoDB Drivers).
- This file is intentionally condensed. For exhaustive operators, stages, and commands, use the referenced MQL, operator, command, and method index pages directly (MQL reference, Query operators, Aggregation operators, mongosh methods).
Cross-hub map — where every MongoDB topic lives
All MongoDB knowledge is split across four hubs (plus mongodb-kb for KB-article lookups and
10gen for repo install/run). If a task’s deep material is not in this hub’s Sub-skill routing
table, it is a reference file under a sibling hub — activate that hub or Read its references/<name>.md directly.
| Hub | Owns | Example reference files |
|---|---|---|
mongodb-expert |
Core data plane + engine internals: CRUD/MQL, aggregation, indexes, query performance, schema design, transactions, change streams, time-series, geospatial, views, BSON, error codes, connection strings, driver internals, WiredTiger cache/eviction/checkpoint internals, mongosh, database tools, multi-tenancy, sharding, replication, Compass | references/mongodb-wiredtiger-internals.md, mongodb-indexes-deep.md, mongodb-sharding.md, mongodb-replication.md |
mongodb-atlas-expert |
Atlas cloud platform: control plane, Atlas Search, Vector Search, Stream Processing, Charts, Data Federation, App Services, Triggers, Online Archive, Flex, networking, IAM/RBAC, Terraform, AKO | references/mongodb-atlas-search.md, mongodb-atlas-vector-search.md |
atlas-diagnostics-expert |
Live diagnostics & performance: ts-diag, FTDC, performance-troubleshooting symptom triage, benchmarking, monitoring/observability, capacity planning | references/mongodb-performance-troubleshooting.md |
mongodb-operations-expert |
Ops & data movement: backup/restore, DR, Ops Manager, upgrades, migration, mongosync, relational migrator, CDC, data lifecycle, security architecture, encryption, compliance, cost, Kafka/Spark connectors | references/mongosync.md, mongodb-backup-restore.md |
High-overlap routing notes:
- Performance symptom triage (high CPU, cache pressure, slow queries, latency spikes) starts at
atlas-diagnostics-expert, but storage-engine root-cause internals (WiredTiger cache fill / dirty trigger / eviction threads / reconciliation / checkpoints) are owned bymongodb-expert— cross-loadmongodb-expert/references/mongodb-wiredtiger-internals.md(andmongodb-wiredtiger.md) for depth. - Migration symptoms vs migration execution: live-cluster diagnosis →
atlas-diagnostics-expert; the migration/mongosync runbook →mongodb-operations-expert. - Atlas Search/Vector query syntax & index design →
mongodb-atlas-expert; the slowness triage of a running search →atlas-diagnostics-expert.