MongoDB Associate Developer study materials
MongoDB Associate Developer study resources

MongoDB Associate Developer cheat sheet

MongoDB Associate Developer · Keep the key ideas within reach.

Quick reference

MongoDB Overview and Architecture

  • A MongoDB deployment stores BSON documents in collections; a collection belongs to a database, and a single mongod process can host many databases.

  • The WiredTiger storage engine (default since 3.0) uses document-level concurrency control, checkpoints, write-ahead journaling, and optional snappy or zstd compression.

  • A replica set has exactly one primary that accepts writes; secondaries replicate the primary's oplog and can serve reads when read preference allows.

  • Sharded cluster components: mongos routers, config servers (a replica set storing metadata), and shards (each a replica set).

  • Read preference modes are primary, primaryPreferred, secondary, secondaryPreferred, and nearest; primary is the default.

  • Read concern levels are local, available, majority, linearizable, and snapshot; write concern values include 0, 1, majority, and tagged sets with optional j (journal) and wtimeout.

  • The 12-byte ObjectId is a 4-byte Unix timestamp, a 5-byte per-process random value, and a 3-byte incrementing counter, so identifiers are roughly time-ordered.

  • Every collection automatically has a unique _id index, and the maximum BSON document size is 16 MB.

Quick reference

CRUD Operations

  • insertMany defaults to ordered:true and stops at the first error; ordered:false continues past errors and returns an array of write errors.

  • replaceOne removes all fields not present in the replacement document but preserves the existing _id; updateOne/updateMany modify only the fields named in operators.

  • Common update operators: $set, $unset, $inc, $mul, $min, $max, $rename, $currentDate, $push, $pull, $addToSet, $pop, $each, $slice.

  • upsert:true inserts a document built from equality conditions in the filter combined with the update operators when no document matches.

  • Query operators include $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $exists, $type, $regex, $elemMatch, $all, $size, and logical $and/$or/$not/$nor.

  • Projections are inclusion or exclusion but not both, except that _id may be excluded in an inclusion projection; {field:0} is the exclusion form.

  • findOneAndUpdate supports returnDocument (before/after, previously returnNewDocument) and is atomic on a single document; bulkWrite batches mixed insert/update/delete ops.

  • deleteMany removes matching documents, deleteOne removes at most one; drop() removes the collection, its documents, and its indexes far faster than deleting all documents.

Quick reference

Indexes and Query Performance

  • Index types: single field, compound, multikey (array field), text, wildcard, hashed, and geospatial (2dsphere); the _id index is unique and created automatically.

  • Compound index prefix rule: an index {a:1,b:1,c:1} supports queries on a, a+b, and a+b+c, but not on b alone.

  • ESR guideline for compound index key order: Equality fields first, then Sort fields, then Range fields.

  • Sort direction matters: an index {a:1,b:-1} serves sort {a:1,b:-1} and {a:-1,b:1}, but not {a:1,b:1}.

  • A multikey index creates one entry per array element; a compound index may include at most one array field.

  • Covered query rule: all filter fields and all projected fields appear in the index, so explain shows no FETCH stage and totalDocsExamined is 0.

  • explain("executionStats") fields to read: stage (COLLSCAN vs IXSCAN), nReturned, totalKeysExamined, totalDocsExamined, and executionTimeMillis.

  • TTL indexes are single-field date indexes with expireAfterSeconds; the background removal thread runs about every 60 seconds.

  • Unique indexes reject duplicates; sparse and partial indexes only contain entries for documents that satisfy the condition.

Quick reference

Aggregation Framework

  • Core stages: $match, $project, $addFields/$set, $group, $sort, $limit, $skip, $unwind, $lookup, $facet, $bucket, $count, $replaceRoot, $out, and $merge.

  • Place $match and $sort as early as possible, and before $group, so they can use indexes and shrink the document stream.

  • In $group the group key is _id (use null for a single group); accumulators include $sum, $avg, $min, $max, $push, $addToSet, $first, $last, $count.

  • $lookup performs a left outer join using localField/foreignField, or a pipeline form with let variables and $expr for correlated sub-queries.

  • $unwind has preserveNullAndEmptyArrays:true to keep documents whose array is missing, null, or empty instead of dropping them.

  • Aggregation stages are limited to 100 MB of RAM each; set allowDiskUse:true to spill to disk when the limit would be exceeded.

  • $out replaces the target collection entirely, while $merge can merge results into an existing collection and requires a unique index on _id.

  • Expression operators include $cond, $switch, $ifNull, $map, $filter, $reduce, $concat, $dateToString, and $sum within a $project.

  • Cursor-like options: .explain(), .allowDiskUse(), and the pipeline stages are executed in array order for every input document stream.

Quick reference

Data Modeling

  • Embed when related data is accessed together and the array is bounded (one-to-few); reference by _id when the relationship is one-to-many/many-to-many, unbounded, or shared.

  • The 16 MB document limit is the hard ceiling that constrains embedding; an unbounded array is the classic modeling error.

  • Model for the application's query patterns and update frequency rather than for third normal form; duplicate data is acceptable if reads dominate and updates are rare.

  • Bucket pattern groups many small time-series or log events into a bounded number of documents, reducing index size and document rewrites.

  • Outlier pattern moves rare oversized documents into a separate collection so the common case stays small and uniform.

  • Extended reference pattern copies a few frequently read fields from a referenced document into the parent to avoid joins, at the cost of periodic resynchronization.

  • Schema versioning adds a version field to documents so mixed old and new shapes can be migrated lazily by the application.

  • Polymorphic pattern stores different shapes of similar entities in one collection and discriminates on a type field, reducing collection sprawl.

  • Attribute pattern moves many similar optional fields into an array of key-value subdocuments so one index covers all of them.

Quick reference

Transactions

  • Multi-document transactions require a replica set (4.0+) or a sharded cluster (4.2+); standalone servers cannot run them.

  • Driver flow: session.startTransaction(), execute operations with that session, then commitTransaction() or abortTransaction().

  • withTransaction() is the recommended helper because it retries on TransientTransactionError and UnknownTransactionCommitResult.

  • Transactions must use readConcern snapshot and typically writeConcern majority; all operations must pass the same session object.

  • transactionLifetimeLimitSeconds defaults to 60 seconds, after which the server aborts the transaction; long transactions also pin the snapshot and oplog.

  • A single-document write is always atomic, so embedding related data often removes the need for a transaction.

  • Not allowed inside transactions: $out, $merge, and operations on views or capped collections; creating collections is limited by server version.

  • Transient transaction errors and write conflicts should be retried at the whole-transaction level, not at the single-statement level.

Quick reference

Drivers and Application Development

  • Connection strings use mongodb:// for explicit host lists and mongodb+srv:// to resolve hosts and options from a DNS SRV record (typical for Atlas).

  • MongoClient is thread-safe and manages a connection pool; create one instance per process rather than per request, and close it on shutdown.

  • maxPoolSize defaults to 100 connections per server; size it against server connection limits and application concurrency.

  • serverSelectionTimeoutMS defaults to 30000 ms; retryWrites is enabled by default on supported deployments.

  • BSON types map to driver types: ObjectId, Decimal128, Date (UTC), Binary, and Int64; use the driver's types rather than strings for binary or decimal data.

  • Error handling distinguishes server selection errors, write errors (for example duplicate key code 11000), and write concern errors.

  • Cursors fetch results in batches via getMore; use batchSize, projections, and eventually close cursors to avoid resource leaks.

  • Change streams use collection.watch() and require a replica set or sharded cluster; resume tokens allow restarting a stream after failure.

Quick reference

Atlas and Developer Tooling

  • Atlas is the managed database service; M0 is a free shared tier, while M10 and above are dedicated clusters with configurable IOPS.

  • Atlas connections require an IP access list entry and a database user; connection strings are typically mongodb+srv:// with a TLS option.

  • mongosh is the modern shell: a Node.js REPL supporting async/await, EJSON output, .mongoshrc.js startup scripts, and load() for script files.

  • MongoDB Compass is the GUI for schema sampling, query building with explain plans, index management, and a visual aggregation pipeline builder.

  • Database Tools include mongodump/mongorestore (binary BSON backups), mongoexport/mongoimport (JSON/CSV), bsondump, mongostat, and mongotop.

  • Atlas Search exposes a $search aggregation stage backed by Apache Lucene indexes; Atlas Vector Search uses the $vectorSearch stage.

  • The Atlas Performance Advisor suggests indexes from slow queries, and the database profiler can be enabled with setProfilingLevel(2).

  • Atlas supports triggers, Atlas Functions, a Data API, and Charts; Atlas backups include continuous cloud backups on dedicated tiers.