Skip to content

MongoDB in Depth ​

"The maximum BSON document size is 16 mebibytes." — MongoDB Manual, Documents, mongodb.com/docs/manual/core/document

Summary: MongoDB stores BSON documents, scales reads with replica sets and writes with sharding, and gives you per-operation dials for durability and consistency; nearly every production problem traces back to the schema, the indexes or the shard key. Focus: The document model and its 16 MB limit, schema design patterns and anti-patterns, every index type and how to read explain, the aggregation pipeline, write/read concerns, transactions, replica sets, sharding, change streams, WiredTiger, security, backups and tooling, with Go driver v2 and Laravel MongoDB code. Learning goal: Design a MongoDB schema from access patterns, index it with ESR and prove it with explain, choose the concern levels for each operation, and operate a replica set or sharded cluster without surprises.

This page is the complete reference for operating MongoDB as an application database: BSON and ObjectId; embedding versus referencing; the bucket, computed, subset, extended reference, attribute, outlier, polymorphic and schema versioning patterns; the anti-patterns the manual names (unbounded arrays, a massive number of collections, bloated documents, unnecessary indexes); single, compound, multikey, text, wildcard, TTL, partial, sparse, hashed and 2dsphere indexes; explain() and the winning plan; the aggregation pipeline from $match to $merge; write concern, read concern, read preference, causal consistency and retryable writes; multi-document transactions on WiredTiger snapshots; replica set elections and the oplog; sharding with shard keys, zones, the balancer and resharding; change streams; WiredTiger internals; $jsonSchema validation; security; backups; and the tooling. It deliberately leaves neighbours to their own pages: where document stores sit among the NoSQL families is NoSQL: Families & Data Models; B-tree versus LSM on disk is Storage Engines; isolation anomalies in general are Isolation Levels; replication theory and failover tooling in general are Replication & Failover; the Go driver in a full service is MongoDB with Go; and the command list is the MongoDB Cheatsheet.

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why a document database, and the trade-off against relationalWhy MongoDB exists
BSON types, the 16 MB limit, ObjectIdThe document model
Embedding vs referencing and the eight named patternsSchema design
Unbounded arrays, too many collections, bloated documents, too many indexesAnti-patterns
Index types, ESR, explain(), the winning planIndexes and explain
$match, $project, $lookup, $group, $facet, $merge, $outAggregation pipeline
w, j, readConcern, read preference, causal sessions, retryable writesConsistency dials
Multi-document transactions, limits, WriteConflict, error labelsTransactions
Elections, oplog, priority, arbiters, hidden and delayed membersReplica sets
Shard key, hashed vs ranged, zones, balancer, reshardingSharding
Change streams and resume tokensChange streams
WiredTiger, knobs, error codesMechanics
$jsonSchema, security, backups, profiler and tools, AtlasOperations
Go driver v2 and Laravel MongoDB codeGo, Laravel
Hot documents, counters, pagination, idempotent upsertsSolving the classic problems
MongoDB or PostgreSQL jsonbChoosing
Monolith to sharded multi-regionIn architecture
A replica set in Docker, write concern, ESR explain, shardingLab
Wrong beliefs, a cheat sheet, every term definedMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The model.

ConceptIn plain wordsTiny exampleThe number to remember
DocumentA JSON-like record stored as BSON{ _id, user_id, items: [...] }16 MB maximum per document
CollectionA set of documents, no fixed columnsordersEvery collection carries an _id index
ObjectIdDefault _id, made by the clientObjectId("665f...")12 bytes: 4 time, 5 random, 3 counter
Single-document atomicityOne document write is all-or-nothing$inc stock and $push a log line togetherNo transaction needed inside one document
Replica setOne primary, secondaries replay its oplog3 data-bearing membersUp to 50 members, 7 voting
Sharded clusterData split by shard key across replica setsmongos + config servers + shardsDefault range size 128 MB

The dials.

DialOptionsSafe defaultWhat it costs
Write concernw: 0, w: 1, w: "majority", j: true, wtimeoutw: "majority" (the server default)Latency of a replica round trip
Read concernlocal, available, majority, linearizable, snapshotlocal for plain reads; majority when you act on what you readPossibly older data, or a primary round trip for linearizable
Read preferenceprimary, primaryPreferred, secondary, secondaryPreferred, nearestprimarySecondaries can be behind (maxStalenessSeconds >= 90)
Causal consistencySession optionOn for sessions in current driversOnly meaningful with majority read and write concerns
Retryable writesretryWrites=trueOn by defaultOne automatic retry; needs an idempotent-by-design write
TransactionsstartTransaction / WithTransactionOnly when one document cannot hold the invariant60 s default lifetime, more cache pressure, WriteConflict aborts

The three things to do.

SituationDo this
Designing a collectionWrite down the top queries first; embed what is read together, reference what grows without bound; pick a pattern by name
Adding an indexOrder compound keys Equality, Sort, Range (ESR), then confirm IXSCAN, no SORT stage and totalKeysExamined close to nReturned in explain("executionStats")
Writing data that mattersw: "majority", retryable writes on, idempotent upserts, and a transaction only when two documents must change together

Why MongoDB exists ​

Relational databases store an aggregate (an order with its lines and its shipping address) as rows across several tables and reassemble it with joins on every read. MongoDB stores the aggregate as one document, so the common read is one index lookup and one document fetch, and the common write is one atomic document update. It also lets each document have a slightly different shape, which suits catalogues with per-category attributes, event payloads and evolving APIs. In exchange you give up the join-everything flexibility and the schema enforcement you get for free in PostgreSQL: you decide up front which queries the shape serves, and you add validation back explicitly.

Relational (PostgreSQL, MySQL)Document (MongoDB)
Model entities; normalise; join at read timeModel access patterns; embed what is read together
Schema enforced by CREATE TABLE and constraintsFlexible by default; enforce with $jsonSchema validators and unique indexes
Multi-row transactions are the normal unitOne document is the normal atomic unit; transactions are the exception
Ad-hoc joins and reporting are cheap to add$lookup exists but is costly at scale; reshape data instead
Scale writes with partitioning, Citus or a distributed SQL engineNative sharding with mongos, a shard key and a balancer
Replication and failover via extra tooling (Patroni etc.)Replica set elections are built in

The analogy we reuse on this page: a clinic's paper case files. Each patient has one folder, and the doctor reads one folder per visit (embedding). The folder cannot grow past the drawer, so years of old visit slips go into dated envelopes in an archive drawer (bucket and subset patterns). The front of each folder repeats the patient's name and blood type so nobody has to open another cabinet (extended reference). The clinic has several copies of the filing cabinet in different rooms (replica set), and when the cabinets fill a room, folders are split across rooms by patient surname (sharding).

Three common misunderstandings, up front ​

  • "Schemaless means no schema." The schema moved into your code and your queries. Without $jsonSchema validation and a schema_version field, it is enforced nowhere.
  • "MongoDB is not ACID." Single-document writes have always been atomic; multi-document transactions exist on replica sets (4.0) and sharded clusters (4.2). The question is cost, not existence.
  • "Sharding fixes slowness." Sharding multiplies capacity for queries that include the shard key. A bad shard key or a missing index makes every query a broadcast across every shard, which is slower than one replica set.

Where it comes from ​

MongoDB began as a document database whose original storage engine (MMAPv1) locked coarsely; WiredTiger replaced it as the default engine and brought document-level concurrency, compression and MVCC snapshots, which every later feature builds on. The version milestones the manual states on the pages used here: retryable writes need MongoDB 3.6+ and featureCompatibilityVersion 3.6+; multi-document transactions need featureCompatibilityVersion 4.0 on replica sets and 4.2 on sharded clusters; "Starting in MongoDB 5.0, you can change your shard key" with reshardCollection; and from 8.0 you can reshard onto the same key to redistribute data. Atlas, the managed service, adds full-text search (Atlas Search, now documented as MongoDB Search) and Vector Search on top of the database.

The data-modeling guidance in the manual rests on one idea: store together what you read together. Its Embedding vs References page frames it as a table. Embed when you have a "has-a" or "contains" relationship, when "Your application queries pieces of information together", or when data is "often updated together". Reference when "The child side of the relationship has high cardinality" or when "Your embedded data grows without bounds". The rest of this page follows from choosing a side of that table per relationship.

The document model ​

BSON and the 16 MB limit Must-know ​

In plain words: BSON is the binary form MongoDB stores and sends; it looks like JSON but has real types for dates, 64-bit integers, decimals, binary and ObjectId, and one document may not exceed 16 MB.

Common misunderstanding: "It is JSON, so numbers are just numbers." A JavaScript 42 from mongosh is a double; from Go int64 it is a long; a validator demanding bsonType: "long" rejects the double. Money stored as double drifts; use Decimal128 or integer cents.

Definition: a document is an ordered set of field/value pairs serialised as BSON. The manual: "The maximum BSON document size is 16 mebibytes." Field order is preserved (it matters for compound _id equality and for sort specifications in commands). Nesting depth is limited to 100 levels. For files above 16 MB, GridFS splits them into chunks.

BSON typeAlias for $type / bsonTypeUse it forTrap
DoubledoubleMeasurementsDefault numeric type from JavaScript
32-bit / 64-bit integerint / longCounters, IDs, centsMixing int and long is fine for queries, not for strict validators
Decimal128decimalMoney, exact decimalsDriver support needed in every client
StringstringUTF-8 textCollation decides case-insensitive comparison
DatedateTimestamps (ms since epoch, UTC)Store UTC; strings sort but do not range-compare as dates
TimestamptimestampInternal (oplog, cluster time)Not for application dates
ObjectIdobjectIdDefault _idNot a secret, not strictly monotonic across clients
Binary databinDataUUIDs (subtype 4), hashes, encrypted fieldsUUID subtype differences between old drivers
Array / Objectarray / objectEmbedded lists and subdocumentsArrays create multikey index entries
Null / missingnullAbsent values{ f: null } matches both null and missing
text
     Session A (append event)                 Session B (append event)            -- one order document with events[]
1    updateOne({_id: 7}, {$push: {events: e1}})
2                                             updateOne({_id: 7}, {$push: {events: e2}})
3    ... after 2 years: document is 15.9 MB, every $push rewrites a huge document in cache
4    updateOne({_id: 7}, {$push: {events: eN}})
     -- error: BSONObjectTooLarge / "Resulting document after update is larger than 16777216" (code 17419)

Real scenarios: an order with every scan event; a chat room document with all messages; a user document with every login; an IoT device with all readings; a product with every review.

Fix: bound every array (subset or bucket pattern), keep large blobs in object storage or GridFS, and model money as Decimal128 or long cents. Code: the bucket pattern and the Go after snippet.

_id and ObjectId Must-know ​

In plain words: every document needs a unique _id; if you do not give one, the driver creates a 12-byte ObjectId that starts with the creation time.

Common misunderstanding: "ObjectId is a good shard key because it is unique." It is roughly increasing, so with ranged sharding every insert goes to the chunk holding maxKey: one hot shard.

Definition: an ObjectId is 12 bytes: a 4-byte timestamp in seconds since the Unix epoch, a 5-byte random value unique to the machine and process, and a 3-byte incrementing counter. The _id field always has a unique index that cannot be dropped. You can use any non-array type as _id: a natural key ("sku-123"), a UUID, or a compound document ({ tenant: 7, order: 991 }).

_id choiceAdvantageCost
ObjectId (default)No round trip, time-ordered, 12 bytesMonotonic: hot spot as a ranged shard key
UUID v4 (binData subtype 4)Random, globally unique, generated anywhere16 bytes; random inserts spread across the B-tree, more cache churn
UUIDv7 / ULIDTime-ordered and globally uniqueSame hot-spot issue as ObjectId for ranged sharding
Natural keyUpsert by business key, no secondary unique indexMust truly never change
Compound _idEncodes tenant + id; one unique indexField order matters for equality matches

Fix: keep ObjectId for most collections, use a natural key when you upsert by it, and never shard by plain ObjectId with ranged sharding (use hashed _id or a compound key). General trade-offs: ID Generation at Scale.

Schema design ​

Start from the workload, not the entities: list the top queries with their frequency and latency target, list the writes, and estimate the cardinality of each relationship (one-to-few, one-to-many, one-to-squillions). Then pick embed or reference per relationship and name the pattern you are applying.

Embedding vs referencing Must-know ​

In plain words: embedding puts the child inside the parent document (one read, one atomic write); referencing stores the child elsewhere with the parent's id (two reads or a $lookup, but no size problem).

Common misunderstanding: "Embed everything, that is the MongoDB way." Embedding a list that keeps growing creates the unbounded-array anti-pattern; embedding data that changes independently forces you to update thousands of copies.

Definition: the manual's rule: embed for "has-a"/"contains" relationships, data queried together and data "often updated together"; reference when "The child side of the relationship has high cardinality" or the embedded data "grows without bounds".

RelationshipExampleRecommended shape
One-to-oneUser and settingsEmbed
One-to-fewOrder and its 1–50 lines; user and 3 addressesEmbed the array
One-to-many (bounded hundreds)Product and its latest reviewsSubset pattern: embed the newest N, reference the rest
One-to-squillionsDevice and its readings; account and its log linesReference from the child (device_id on each reading), or bucket
Many-to-manyStudents and coursesArrays of ids on one or both sides, plus extended references for display fields
Shared, changing entityProduct price in every orderReference, or copy deliberately as a snapshot (the order should keep the price at purchase time)
text
     Embedded (one read)                         Referenced (two reads)
1    find({_id: order_id})                       find({_id: order_id})
2    -> order + lines + address, one document    -> order with customer_id
3                                                find({_id: customer_id})   -- or $lookup in one pipeline
     -- 1 index lookup, atomic update of lines   -- 2 lookups, lines can grow without touching the order

Real scenarios: a checkout reading an order with its lines (embed); a CMS page with all comments (reference or subset); a SaaS tenant with its users (reference: thousands of users, each edited independently); an invoice snapshotting the customer's billing address at the time of sale (embed a copy on purpose).

The named design patterns Must-know ​

PatternProblem it solvesShapeCost
BucketToo many tiny documents (time series, events)One document holds up to N items of a seriesBucket management code; partial buckets
ComputedThe same expensive aggregation on every readStore the running total/count; update on writeWrites do more; value can drift if a writer forgets
SubsetHot document too big because of a long listEmbed the newest/most-used N, keep the full list in another collectionTwo writes per new item
Extended referenceConstant $lookup just to show a nameCopy the few display fields of the referenced document next to the referenceCopies go stale; refresh on change or accept a snapshot
AttributeMany sparse, similar fields that all need indexesattrs: [{k: "color", v: "red"}, ...] with one index on { "attrs.k": 1, "attrs.v": 1 }Queries become $elemMatch; validation is harder
OutlierA few documents are far bigger than the restFlag the outlier (has_overflow: true) and move the excess to overflow documentsCode path for the outlier
PolymorphicDifferent shapes of the same thing in one collectionOne collection, a type field, shared fields indexedValidation per type with oneOf
Schema versioningChanging shape without a stop-the-world migrationschema_version field; code reads both versions; migrate lazilyTwo code paths until the backfill ends

Related patterns the manual also lists: archive (move cold data to cheaper storage) and single-collection (several entity types sharing one collection keyed for one access pattern).

Bucket pattern Must-know ​

In plain words: instead of one document per reading or event, put up to N readings into one document, so the number of documents and index entries drops by a factor of N.

Common misunderstanding: "Buckets are only for IoT." Any append-only series per key benefits: order events, chat messages per room per day, page views per article per hour. Time series collections apply the same idea internally for measurements.

Definition: the manual: "The bucket pattern separates long series of data into distinct objects." Each bucket carries the key, a count or time window, the items and often precomputed aggregates (sum, min, max) so it doubles as a computed pattern.

text
     Writer                                                   -- order_event_buckets, bucket size 200
1    updateOne({order_id: 7, count: {$lt: 200}},
               {$push: {events: e}, $inc: {count: 1}}, {upsert: true})
2    -> matches the open bucket (count 199) -> count 200
3    updateOne(... same filter ...)
4    -> no bucket with count < 200 -> upsert creates a new bucket with count 1
     -- an index on {order_id: 1, count: 1} keeps step 1 an IXSCAN

Real scenarios: shipment scan events; sensor readings per device per hour; chat messages per room per day; audit log lines per user per month.

Fix / how to use it: the upsert above is in the Go after snippet and the Laravel After.php. Add an index that serves the bucket filter, and cap buckets by count or by time window, not both unless you need it.

Computed and subset patterns Important ​

In plain words: computed means "store the answer, not just the inputs" (a product's review_count and rating_avg); subset means "keep only the part you show often inside the document" (the 10 newest reviews).

Common misunderstanding: "A computed field is a cache, so it is optional to keep correct." If every write path does not update it in the same atomic operation, it drifts. Update it with $inc in the same updateOne as the change, or recompute periodically with $merge.

Definition: the computed pattern stores derived values updated on write or on a schedule. The subset pattern keeps a bounded subset of a related list embedded; the manual: "MongoDB keeps frequently accessed data, referred to as the working set, in RAM", so smaller hot documents keep more of them in cache.

js
// computed + subset in one atomic update on the product document
db.products.updateOne(
  { _id: productId },
  {
    $inc: { review_count: 1, rating_sum: 5 },
    $push: { recent_reviews: { $each: [review], $sort: { at: -1 }, $slice: 10 } }
  }
)
db.reviews.insertOne(review) // the full list lives in its own collection

Real scenarios: product page with rating and last 10 reviews; a user profile showing follower count; an account with its current balance next to an append-only ledger collection.

Extended reference, attribute, outlier, polymorphic and schema versioning Important ​

In plain words: extended reference copies a few fields of the referenced document; attribute turns many optional fields into key/value pairs; outlier treats the rare giant document differently; polymorphic keeps several shapes in one collection; schema versioning tags each document with the shape it uses.

Common misunderstanding: "Duplicated data is a bug." In MongoDB, duplicating stable display fields (customer name on an order) is an intended trade: faster reads for occasional fan-out updates. The manual's Handle Duplicate Data page treats it as a design decision, not an error.

Definition and shape:

js
// extended reference: order keeps customer_id plus the display fields it needs
{ _id: 991, customer: { _id: 42, name: "Sara K.", city: "Berlin" }, lines: [ /* ... */ ] }

// attribute: one index serves every attribute query
{ _id: "sku-1", attrs: [ { k: "color", v: "red" }, { k: "size_eu", v: 42 } ] }
db.products.createIndex({ "attrs.k": 1, "attrs.v": 1 })
db.products.find({ attrs: { $elemMatch: { k: "color", v: "red" } } })

// outlier: a book with 1M buyers keeps the first 1000 inline and flags overflow
{ _id: "book-9", buyers: [ /* 1000 ids */ ], has_overflow: true }

// polymorphic + schema versioning
{ _id: 1, type: "card",   schema_version: 2, last4: "4242", network: "visa" }
{ _id: 2, type: "wallet", schema_version: 1, provider: "paypal" }

Real scenarios: orders showing customer name without $lookup (extended reference); a marketplace with 400 category-specific attributes (attribute); a celebrity account with 50 million followers among ordinary users (outlier); payments of several kinds (polymorphic); renaming address to addresses[] without downtime (schema versioning, migrated lazily on read-then-write and finished by a background job).

PatternIndex you needValidation approach
Extended referenceIndex on the reference _id for fan-out refreshRequired display fields
Attribute{ "attrs.k": 1, "attrs.v": 1 }attrs items require k and v
OutlierSame as normal documents; overflow keyed by parent idhas_overflow is boolean
PolymorphicShared fields plus partial indexes per type$jsonSchema with oneOf per type
Schema versioningUsually none extra; optionally partial index on old version for the backfillschema_version required

Anti-patterns ​

Unbounded arrays, massive number of collections, bloated documents, unnecessary indexes Must-know ​

In plain words: four shapes the manual warns about: arrays that grow forever, a new collection per day/tenant/user, documents carrying fields nobody reads with them, and an index for every field.

Common misunderstanding: "More indexes always make reads faster." Each index costs RAM in the WiredTiger cache, disk, and work on every insert and update; unused ones only slow writes.

Definition (the manual's words): unbounded arrays: "if you do not limit the number of elements in an array, your documents might exceed the 16MB BSON document size limit. An unbounded array can strain application resources and decrease index performance." Massive number of collections: "Creating too many collections can decrease performance. With every collection, MongoDB creates a default _id index, which uses additional storage." Bloated documents: "Storing data fields that are related to each other but not accessed together can create bloated documents that lead to excessive RAM and bandwidth usage." Unnecessary indexes: "Unnecessary indexes might be rarely used, redundant due to coverage by another compound index, or not used at all."

Anti-patternSymptom you seeFix
Unbounded arraysSlow $push, rising document size, error 17419 near 16 MBSubset, bucket, or reference from the child
Massive number of collectionsThousands of _id indexes, slow startup, high file-handle countOne collection with a discriminator field (day, tenant_id) and a compound index
Bloated documentsWorking set does not fit in cache; high bytes read per querySplit rarely read fields (description, history) into another collection
Unnecessary indexesWrite latency up, $indexStats shows accesses.ops: 0Drop unused and prefix-redundant indexes ({a:1} is covered by {a:1,b:1})
Case-insensitive queries without a collation index$regex: /^x/i does a scanIndex with a case-insensitive collation and query with the same collation
Separating data that is accessed together$lookup on every requestEmbed or extended reference
js
// find unused indexes since the last restart
db.orders.aggregate([{ $indexStats: {} }, { $project: { name: 1, "accesses.ops": 1 } }])
// hide before dropping: the planner ignores it but it is still maintained
db.orders.hideIndex("status_1")

Indexes and explain ​

MongoDB indexes are B-trees (WiredTiger stores them with prefix compression). Without a usable index a query is a COLLSCAN: every document is read. How B-trees work in general is in Indexing and B-Tree vs B+Tree; this section is about the MongoDB-specific types and rules.

Index types Must-know ​

In plain words: one B-tree mechanism, many flavours: on one field, on several fields in order, on array elements, on words, on unknown field names, with an expiry, on a subset of documents, on hashes, or on geographic shapes.

Common misunderstanding: "Sparse and partial are the same." A sparse index skips documents missing the field; a partial index skips documents not matching any filter you choose. The manual: "Partial indexes can function as sparse indexes, but also support filter expressions for conditions beyond whether a field exists."

TypeCreateServesLimits and traps
Single fieldcreateIndex({ email: 1 })Equality, range, sort on that fieldDirection irrelevant for single-field sorts
CompoundcreateIndex({ user_id: 1, status: 1, created_at: -1 })Queries on any prefix; sort in index order or its reverseOrder follows ESR; mixed directions must match the sort
MultikeyAutomatic when an indexed field holds an arrayMatching any elementOne entry per element; at most one array field per compound index key
TextcreateIndex({ title: "text", body: "text" })$text: { $search: "..." } with stemming"A collection can have only one text index"; for relevance search use Atlas Search
WildcardcreateIndex({ "attrs.$**": 1 })Queries on unknown or arbitrary subfieldsCannot serve compound sorts like a planned compound index
TTLcreateIndex({ last_seen: 1 }, { expireAfterSeconds: 3600 })Automatic deletionBackground monitor; documents may linger up to about 60 s after expiry; single date field
PartialcreateIndex({ created_at: 1 }, { partialFilterExpression: { status: "open" } })Queries whose filter implies the expressionQuery must include the filter condition to use it
SparsecreateIndex({ coupon: 1 }, { sparse: true, unique: true })Unique on optional fieldsSorts using it can silently skip documents
HashedcreateIndex({ tenant_id: "hashed" })Equality; hashed shardingNo range queries; no arrays; no unique
2dspherecreateIndex({ location: "2dsphere" })$near, $geoWithin, $geoIntersects on GeoJSONCoordinates are [longitude, latitude]
UniquecreateIndex({ email: 1 }, { unique: true })ConstraintE11000 duplicate key error on violation
Clustered / hiddencreateCollection(..., { clusteredIndex }) / hideIndex()Storage ordered by key / test a dropHidden index is still maintained on writes

The ESR guideline Must-know ​

In plain words: in a compound index, put the fields you match exactly first, then the field you sort by, then the fields you filter by range.

Common misunderstanding: "Put the most selective field first." In MongoDB the order is about what the B-tree can do: equality fields narrow to one contiguous slice, after which entries are already in sort order; a range before the sort breaks that order and forces an in-memory SORT.

Definition: the manual: "Ensure that equality fields always come first." Then sort fields, then range fields. The documented exception: "If your range predicate in the query is very selective, then put it before sort fields (ERS)". Note that $ne, $nin and $regex are range operators for this rule, and $in behaves as equality for filtering but can break sort order across several values.

text
     Query: find({user_id: 42, status: "open", total_cents: {$gte: 5000}}).sort({created_at: -1})
1    Index A {user_id:1, status:1, total_cents:1, created_at:-1}   (E E R S)
2      IXSCAN on total_cents >= 5000 -> keys not in created_at order -> SORT stage in memory
3    Index B {user_id:1, status:1, created_at:-1, total_cents:1}   (E E S R)
4      IXSCAN walks created_at descending inside (42, "open"); total_cents checked on index keys
5      -> no SORT stage; can stop early with limit(20)

Real scenarios: "my open orders, newest first, above a value"; "tickets for tenant X with status Y sorted by priority"; "messages in room R after timestamp T, newest first" (here the range and the sort are the same field, so E then S/R).

Reading explain() and the winning plan Must-know ​

In plain words: explain() shows which plan the query planner chose (the winning plan), which ones it rejected, and with "executionStats" how many keys and documents it really touched.

Common misunderstanding: "IXSCAN means the query is fine." An IXSCAN that examines 200,000 keys to return 20 documents, followed by a SORT, is a bad plan with an index in it.

Definition: the planner generates candidate plans from the available indexes, races them for a trial period, caches the winner in the plan cache per query shape, and re-plans when performance degrades. explain verbosity: "queryPlanner" (default, plans only), "executionStats" (runs the winning plan), "allPlansExecution" (also trial stats of the rejected plans). When the slot-based execution engine (SBE) runs the query, the output nests the plan under winningPlan.queryPlan and adds a slotBasedPlan.

Field or stageMeaningHealthy value
queryPlanner.winningPlanThe chosen tree of stagesFETCH over IXSCAN, or PROJECTION_COVERED over IXSCAN
rejectedPlansPlans that lost the raceMany rejected plans suggest overlapping indexes
COLLSCANFull collection scanOnly on tiny collections or deliberate full scans
IXSCAN with indexBoundsIndex range scannedTight bounds on the equality prefix
SORT / SORT_KEY_GENERATORIn-memory sortAbsent for paginated queries
FETCH with filterDocuments loaded then filteredFilter should be small; move fields into the index
executionStats.nReturnedDocuments returnedClose to totalKeysExamined
totalKeysExamined / totalDocsExaminedWork doneRatio to nReturned near 1; totalDocsExamined: 0 means covered
executionTimeMillisTime of the winning planStable across runs
SHARD_MERGE / SINGLE_SHARDSharded: broadcast vs targetedSINGLE_SHARD for OLTP queries
js
db.orders.find({ user_id: 42, status: "open", total_cents: { $gte: 5000 } })
  .sort({ created_at: -1 }).limit(20)
  .explain("executionStats")
// winningPlan: { stage: 'LIMIT', inputStage: { stage: 'FETCH', inputStage: { stage: 'IXSCAN',
//   indexName: 'user_id_1_status_1_created_at_-1_total_cents_1', ... } } }
// executionStats: { nReturned: 20, totalKeysExamined: 40, totalDocsExamined: 20, ... }   (lab run, mongo:8.0)

Aggregation pipeline ​

Stages and their order Must-know ​

In plain words: an aggregation pipeline is a list of stages; each stage takes documents in and passes documents out, like Unix pipes.

Common misunderstanding: "The optimiser will fix my stage order." It moves some filters and coalesces some stages, but it cannot make a $match placed after $group or $lookup use an index, and it never removes a $lookup you did not need.

Definition: the manual's advice: "When possible, put $match at the beginning of the pipeline to use indexes that scan the matching documents in a collection." $group is blocking: "If the $group stage exceeds 100 megabytes of RAM, MongoDB writes data to temporary files. However, if the allowDiskUse option is set to false, $group returns an error." $lookup is a left outer join, and "Unindexed or correlated-subquery $lookup operations on large collections can slow down query performance."

orders1,000,000 docs$matchIXSCAN on ESR2,000 docs out$projectkeep 3 fieldssmaller docs$lookupcustomers by _idindex on foreignField$groupblocking; 100 MBthen spill to disk$facetsame input,many sub-pipelines$sort + $limit 10(top-k sort)$buckethistogram$merge / $outupsert into reports.daily_revenueOptimiser rules that matter1. $match first: only a leading $match or $sort can use an index2. filters after $project / $set are moved ahead when independent3. $sort + $limit coalesce: keep only k docs in memory4. $lookup + $unwind coalesce into one stage5. narrow early: fewer, smaller docs per stage6. on a sharded cluster, $match on the shard key targets one shard; $group merges on one node
StageWhat it doesOptimisation note
$matchFilters documentsFirst, so it can use an index; on sharded clusters include the shard key
$project / $set / $unsetReshape, add or remove fieldsEarly narrowing cuts memory; the optimiser moves independent $match before them
$sort + $limitOrder and cutCoalesce into a top-k sort; a leading $sort can use an index
$lookupLeft outer join to another collectionIndex foreignField; $lookup + $unwind coalesce; prefer embedding for hot paths
$unwindOne document per array elementMultiplies document count; filter first
$groupGroup by key with accumulators ($sum, $avg, $push, $addToSet)Blocking; 100 MB per stage, then spill (allowDiskUse); $push can exceed it with no spill
$facetSeveral sub-pipelines on the same inputThe single output document must stay under 16 MB; as the first stage it does a COLLSCAN, so put $match before it
$bucket / $bucketAutoHistogramsGood inside $facet
$mergeUpsert results into a collection (incremental materialised view)Can write to a sharded collection; whenMatched / whenNotMatched
$outReplace a collection with the resultsAtomic replace that keeps the old collection's index definitions; cannot output to a sharded collection (use $merge)
$unionWithAppend another collection's resultsLike UNION ALL
$setWindowFieldsWindow functions (running totals, ranks)Partition by an indexed key
$search / $vectorSearchAtlas Search / Vector SearchMust be the first stage
js
db.orders.aggregate([
  { $match: { status: "paid", created_at: { $gte: ISODate("2026-11-01") } } }, // index
  { $project: { customer_id: 1, total_cents: 1 } },
  { $group: { _id: "$customer_id", revenue: { $sum: "$total_cents" }, orders: { $sum: 1 } } },
  { $lookup: { from: "customers", localField: "_id", foreignField: "_id", as: "c" } },
  { $unwind: "$c" },
  { $facet: {
      top10: [ { $sort: { revenue: -1 } }, { $limit: 10 } ],
      histogram: [ { $bucket: { groupBy: "$revenue", boundaries: [0, 10000, 100000, 1000000] } } ]
  } },
  { $merge: { into: "report_revenue_daily", whenMatched: "replace", whenNotMatched: "insert" } }
], { allowDiskUse: true })

Real scenarios: a nightly revenue rollup with $merge into a reporting collection; a search results page with $facet for counts per category and the first page of hits; a leaderboard with $setWindowFields; a GDPR export joining a user's orders with $lookup.

Consistency dials ​

Write concern Must-know ​

In plain words: write concern is how many replica set members must have your write, and whether it must be in the journal, before the server says "OK".

Common misunderstanding: "j: true makes a write durable." It makes it durable on the primary's disk. The manual: j: true "alone does not guarantee that the write will not roll back due to replica set primary failover." Only a majority-acknowledged write survives an election.

Definition: { w: <n | "majority" | tag>, j: <bool>, wtimeout: <ms> }. "The default global write concern is majority", with one documented edge case: with arbiters, if the data-bearing voting members are not more than the voting majority, the implicit default is { w: 1 } (a PSA set). wtimeout only stops waiting; it does not undo the write, which may still replicate.

text
     Client                     Primary P                   Secondary S1            Secondary S2
1    insert {w: 1}  ------->    apply, journal later
2    <------- ack (fast)
3                               P crashes before S1/S2 pulled the entry
4                                                           S1 elected primary
5                               P rejoins: the write is ROLLED BACK (written to a rollback file)
     -- with {w: "majority"} step 2 waits until P + S1 have it; S1 or S2 elected keeps it
Write concernAcknowledged whenSurvives failover?Typical use
w: 0Never (fire and forget)No, and you never learn of errorsMetrics you can lose
w: 1Primary applied it in memoryNoLogs, caches, high-volume telemetry
w: 1, j: truePrimary journaled itSurvives primary restart, not failoverSingle-node durability
w: "majority"Majority of data-bearing voting members applied it (journaled by default)YesDefault; orders, payments, anything you act on
w: <tag>Members matching a tag set (e.g. two data centres)Yes, across zonesMulti-DC durability

Read concern Must-know ​

In plain words: read concern decides which version of the data a read may return: the latest the node has, only what a majority has, or a consistent snapshot.

Common misunderstanding: "Reading from the primary always gives me committed data." With the default local read concern a read can return a w: 1 write that is later rolled back.

Definition: the levels are local (the node's latest data; default for reads), available (like local, may return orphaned documents on sharded clusters), majority (the manual: "The query returns the data acknowledged by a majority of the replica set members. Returned documents are durable, even if a failure occurs."), linearizable (reflects all majority-acknowledged writes that completed before the read; primary only, single document) and snapshot (a point-in-time view, in transactions and for some reads).

Read concernCan return data later rolled back?Sees your own w: 1 write?Cost
localYesYes on the primaryCheapest
availableYes (and orphans on shards)UsuallyCheapest on sharded clusters
majorityNoOnly after it is majority-committedPossibly slightly old data
linearizableNoYes, and every completed majority writeRound trip to confirm primary; use maxTimeMS
snapshotNo (with majority commit)Inside its transactionHolds a snapshot open: cache pressure

Read preference Important ​

In plain words: read preference decides which member serves your read: the primary, a secondary, or the nearest by latency.

Common misunderstanding: "Reading from secondaries scales my reads for free." Secondaries apply the same writes as the primary, so they are not idle; they lag; and reading your own write from a secondary right after writing usually misses it.

Definition: modes primary (default), primaryPreferred, secondary, secondaryPreferred, nearest, plus tag sets ({ dc: "eu" }) and maxStalenessSeconds. The manual: "You must specify a maxStalenessSeconds value of 90 seconds or longer". Hidden and delayed members never serve reads.

ModeReads fromUse forRisk
primaryPrimary onlyRead-your-writes, anything you act onUnavailable during an election
primaryPreferredPrimary, else a secondaryAvailability during failoverStale reads during failover
secondarySecondaries onlyIsolated analyticsLag; errors if no secondary
secondaryPreferredSecondary, else primaryDashboards, exportsLag
nearestLowest latency memberGeo-distributed read-mostly dataLag; combine with tags

Causal consistency and retryable writes Important ​

In plain words: a causally consistent session promises that within that session you read your own writes and see operations in order, even across members; retryable writes let the driver resend a write once after a network error or failover without applying it twice.

Common misunderstanding: "Sessions are causally consistent whatever the concerns." The manual: "The use of read concern "local" and write concern { w: 1 } in a causally consistent session cannot guarantee causal consistency." You need majority on both sides for all four guarantees (read your writes, monotonic reads, monotonic writes, writes follow reads) to survive failures.

Definition: the session carries operationTime and clusterTime; a later read sends afterClusterTime so the serving member waits until it has caught up. Retryable writes: the driver attaches a transaction number to the write; on a retryable error it retries once, and the server deduplicates by session and transaction number. Supported: single-document inserts, updates, deletes, findAndModify, and bulk writes without multi-document updateMany/deleteMany. "Writes inside a transaction are not individually retryable, regardless of value of retryWrites." Writes with w: 0 are not retried.

text
     App (causal session, majority/majority)       Primary P            Secondary S (lag 2 s)
1    update profile (w: majority) ------------->   applied at T=100
2    <------------ ack, operationTime = 100
3    read profile, readPreference secondary,
     afterClusterTime = 100 ------------------------------------------>  waits until it applied T=100
4    <------------------------------------------------------------------ returns the new profile
     -- without the session the read in 3 could return the old profile

Fix: Go: client.StartSession(options.Session().SetCausalConsistency(true)) plus mongo.NewSessionContext; see the consistency snippet. Laravel: keep reads that must see a write on the primary (default read preference), and send lag-tolerant reads to secondaries with ->readPreference(ReadPreference::SECONDARY_PREFERRED).

Transactions ​

Multi-document transactions Must-know ​

In plain words: a transaction lets several documents, in several collections (and on sharded clusters, several shards), change all-or-nothing, reading from one snapshot.

Common misunderstanding: "Transactions make MongoDB relational." The manual: "In most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed transactions should not be a replacement for effective schema design."

Definition: transactions run in a session; reads see a WiredTiger snapshot taken at the first operation (snapshot isolation; see Isolation Levels for what that allows, including write skew). Writes take document locks. A write to a document that another transaction already modified fails with WriteConflict (code 112) and the transaction must be retried. A non-transactional write to a document a transaction has locked waits; a transaction that later touches a document changed outside it aborts. Commit with w: "majority" to get the snapshot guarantee on committed data.

Limit or behaviourValue / rule
DeploymentReplica set (FCV 4.0+) or sharded cluster (FCV 4.2+); not a standalone mongod
Lifetime"By default, a transaction must have a runtime of less than one minute"; transactionLifetimeLimitSeconds
Lock wait inside a transactionmaxTransactionLockRequestTimeoutMillis, then abort (also hit when DDL is pending on the same collection)
SizeMany oplog entries per transaction; each entry still under 16 MB
Cache pressureBig transactions abort with WriteConflict or TransactionTooLargeForCache
Write concernSet on the transaction, never per operation inside it (error)
Not allowedWrites to capped collections and system.* collections; creating collections and indexes is allowed, with restrictions (read concern local)
Sharded with arbitersTransactions that write to a shard with an arbiter error and abort
text
     T1 (reserve seat 14A)                          T2 (reserve seat 14A)
1    startTransaction (snapshot at t=10)
2                                                   startTransaction (snapshot at t=10)
3    updateOne({seat: "14A", free: true}, {$set: {free: false, by: 1}})   -- locks doc
4                                                   updateOne({seat: "14A", free: true}, ...)
5                                                   -> WriteConflict (112), label TransientTransactionError
6    commitTransaction -> ok
7                                                   abort; driver retries whole callback:
8                                                   new snapshot sees free: false -> 0 matched -> app says "taken"
Error / labelMeaningWhat to do
WriteConflict (112)Another writer changed the document firstRetry the whole transaction (the label says so)
Label TransientTransactionErrorWhole transaction can be retried safelyRe-run the callback from the start
Label UnknownTransactionCommitResultCommit outcome unknown (network, failover)Retry commitTransaction only; it is idempotent
NoSuchTransaction (251)Transaction aborted or expired (lifetime limit)Retry from the start; shorten the transaction
TransactionTooLargeForCacheTransaction cannot fit in the WiredTiger cacheSplit the work; it will never succeed as is
E11000 duplicate key (11000)Unique index violatedBusiness error, not retryable

Fix: use the convenient API: Go session.WithTransaction(ctx, fn) "Errors with the TransientTransactionError and UnknownTransactionCommitResult labels are retried for up to 120 seconds"; Laravel DB::connection('mongodb')->transaction(fn () => ..., attempts: 3). Keep the callback idempotent and short, and do side effects (emails, HTTP) after commit.

Replica sets ​

Elections, oplog, priority, arbiters, hidden and delayed members Must-know ​

In plain words: a replica set is several copies of the same data; one member (the primary) takes writes and records them in the oplog, the others (secondaries) copy and replay the oplog, and if the primary disappears they vote a new one.

Common misunderstanding: "Two data nodes plus an arbiter is as good as three data nodes." With one data node down, w: "majority" writes cannot be acknowledged (the arbiter has no data), majority-committed reads stall and cache pressure grows; the manual documents PSA performance issues.

Definition: "A replica set can have up to 50 members, but only 7 voting members." Members send heartbeats "every two seconds"; when the primary is unreachable for electionTimeoutMillis ("10 seconds by default") an eligible secondary calls an election (protocol version 1, Raft-like terms). "The median time before a cluster elects a new primary should not typically exceed 12 seconds". "The replica set cannot process write operations until the election completes successfully." The oplog is the capped collection local.oplog.rs; "Each operation in the oplog is idempotent". Its default size is 5% of free disk, bounded between 990 MB and 50 GB; oplogMinRetentionHours keeps entries for at least a given time. If a secondary falls behind the oplog window it needs a full initial sync.

App / driverw: "majority"1 writePRIMARY (priority 2)2 apply + append oploglocal.oplog.rs (capped)ts 101 | ts 102 | ts 103SECONDARY Aapplied up to ts 103SECONDARY Bapplied up to ts 102 (lag)3 pull + replay4 ack after 2 of 3voting membersHIDDEN: priority 0, invisibleto clients (analytics, backup)DELAYED: secondaryDelaySecs= 3600 (undo a bad delete)Failover timelinet0 primary diesheartbeats every 2 sgo unansweredwrites failt0 + 10 selectionTimeoutMillisA calls election,term + 1, asks votesmajority votes yes(freshest oplog,highest priority)A is new PRIMARYold primary returnsas secondary; w:1writes it alone hadare ROLLED BACK
Member typeVotesCan become primaryServes readsUse
Primary1Is primaryYesAll writes
Secondary (priority > 0)1YesWith read preferenceFailover target
Priority 00 or 1NoYesA DR site that should never lead
Hidden0 or 1No (must be priority 0)No ("invisible to client applications")Analytics, backups
Delayed0 or 1No (priority 0, should be hidden)NosecondaryDelaySecs window to undo human error
Arbiter1 ("exactly 1 election vote")No (no data)NoTie-breaker when a third data node is impossible
Non-voting0NoYesRead scaling beyond 7 voters

Real scenarios: a 3-member set across three availability zones (the default production shape); a 5-member set across two regions plus a tie-breaker in a third; a hidden member for nightly mongodump and BI; a delayed member one hour behind that saved a team from a deleteMany({}) run on production.

Rollback: writes acknowledged with w: 1 and not replicated when the old primary fails are rolled back when it rejoins, saved to rollback files under the data directory. w: "majority" writes are never rolled back.

Sharding ​

Shard key, hashed vs ranged, zones, balancer and resharding Must-know ​

In plain words: sharding splits one collection across several replica sets by a shard key; mongos routers look up which shard owns which key range and send each query only where it needs to go.

Common misunderstanding: "I will pick the shard key later." Every query without the shard key becomes a broadcast to every shard, and every insert with a monotonically increasing key lands on the same shard. Changing the key later is possible (reshardCollection) but copies the whole collection.

Definition: "The mongos acts as a query router, providing an interface between client applications and the sharded cluster." Config servers (a replica set) hold the metadata: which chunk (a contiguous shard-key range) lives on which shard. The balancer, "a background process that monitors the amount of data on each shard", migrates ranges when shards differ by three times the range size ("For the default range size of 128MB, two shards must have a data size difference for a given collection of at least 384MB for a migration to occur"). A good shard key has high cardinality, low frequency (no single hot value) and appears in most queries. "A shard key on a value that increases or decreases monotonically is more likely to distribute inserts to a single chunk within the cluster".

App (Go / Laravel)App (workers)mongosmongosConfig server replica setconfig.chunks: range to shardzones, balancer settingscache routing tabletargeted:filter has keybroadcast (scatter-gather): no shard keyshard A (replica set)zone EU[minKey, 1000)[1000, 2000)[2000, 3000)shard B (replica set)zone EU[3000, 4000)shard C (replica set)zone US[4000, maxKey)balancer: range migration A to B (inside zone EU)Shard key { tenant_id: 1, order_id: 1 }. Default range size 128 MB; migrate when shards differ by 3 x range size.
StrategyHow keys map to shardsGood atBad at
Ranged shardingContiguous key rangesRange queries on the key, zone placementMonotonic keys: one hot shard
Hashed shardingRanges of the hash of the keyEven write spread for monotonic keysRange queries become broadcasts
Compound key ({ tenant_id: 1, _id: 1 })Ranges over the pairTargeted per-tenant queries, spread within a tenantVery large single tenants need a hashed suffix
ZonesKey ranges pinned to tagged shardsData residency (EU data on EU shards), hot/cold tiersBalancer only moves within the zone
text
     Query routing on {tenant_id: 1, order_id: 1}
1    find({tenant_id: 7, order_id: 991})   -> mongos: one range -> SINGLE_SHARD (targeted)
2    find({tenant_id: 7})                  -> prefix of the key -> one or a few shards (targeted)
3    find({status: "open"})                -> no key -> every shard, SHARD_MERGE (broadcast)
4    updateOne({status: "open"}, ...)      -> must include the shard key or _id (or use updateMany)
5    sh.reshardCollection("shop.orders", {tenant_id: 1, created_at: 1}) -> copy, catch up, cut over
OperationCommandNote
Shard a collectionsh.shardCollection("shop.orders", { tenant_id: 1, order_id: 1 })Needs a supporting index
Hashedsh.shardCollection("shop.events", { device_id: "hashed" })Pre-split for empty collections
Zonessh.addShardToZone("shardA", "EU"), sh.updateZoneKeyRange(...)Key ranges per zone
Balancersh.getBalancerState(), sh.stopBalancer(), balancing windowsStop during backups
Range sizechunksize in config.settings (default 128 MB)Larger = fewer migrations
Refine keyrefineCollectionShardKeyAdds suffix fields, no data copy
ReshardreshardCollection (5.0+), same key with forceRedistribution (8.0+)Needs disk for a full copy; one such operation at a time
Unshard / moveunshardCollection, moveCollectionMutually exclusive with resharding

Real scenarios: multi-tenant SaaS on { tenant_id: 1, _id: 1 }; IoT events on hashed device_id; EU tenants pinned with zones; a team that sharded on created_at and had one shard at 100% CPU until they resharded on { device_id: "hashed" }. The conceptual side of splitting data is in Storage & Data Scaling and Consistent Hashing.

Change streams ​

Change streams and resume tokens Important ​

In plain words: a change stream is a cursor that never ends: it returns every insert, update, replace and delete on a collection, database or cluster, in order, and you can resume after a crash from the last token you saved.

Common misunderstanding: "Change streams are a message broker." They are bounded by the oplog window: if a consumer is down longer than the oplog retains, the resume token is gone and you must re-snapshot. They also do not fan out across consumers like a consumer group.

Definition: the manual: change streams let applications "access real-time data changes without the prior complexity and risk of manually tailing the oplog", on replica sets and sharded clusters. Each event's _id is its resume token; pass it as resumeAfter or startAfter, or start at a cluster time with startAtOperationTime. fullDocument: "updateLookup" adds the current document to update events; pre- and post-images can be enabled per collection (changeStreamPreAndPostImages). Change streams report majority-committed changes, so a stream does not show writes that will later roll back.

text
     Writer                         Change stream consumer (projection to search index)
1    insert order 1  (token A)
2                                   next() -> insert 1; index it; save token A
3    update order 1  (token B)
4                                   next() -> update 1; consumer crashes before saving B
5                                   restart: watch(resumeAfter: A) -> update 1 again (idempotent upsert)
     -- if downtime exceeds the oplog window: ChangeStreamHistoryLost -> full resync

Real scenarios: cache invalidation; updating Elasticsearch or Atlas Search projections; an outbox relay (write the event document in the same transaction, stream it to Kafka; see Transactional Outbox and Change Data Capture); audit feeds.

What each database really does ​

MongoDB's features have counterparts elsewhere; naming them makes the choice concrete.

CapabilityMongoDBPostgreSQLMySQL InnoDBOthers
Document storageNative BSON, 16 MB per documentjsonb column (binary, up to 1 GB per value via TOAST)JSON column (binary, max_allowed_packet bound)SQLite JSON1 functions on text; Redis JSON module; SQL Server and Oracle JSON types
Indexing inside documentsAny path, multikey, wildcardGIN on jsonb (jsonb_path_ops), expression indexesMulti-valued and functional indexesCockroachDB inverted indexes on JSONB
Atomic unitSingle document; transactions optionalAny transactionAny transactionCassandra: partition; DynamoDB: item (+ transactions)
Default write durabilityw: "majority"Local commit, synchronous_commit on; replicas async by defaultLocal commit; replicas async by defaultCockroachDB: Raft majority on every write
Built-in failoverReplica set electionsNo (Patroni, cloud managed)Group Replication / InnoDB ClusterCockroachDB, Spanner: consensus built in
Built-in shardingYes (mongos, balancer)No (Citus, partitioning)No (Vitess)CockroachDB, Spanner, Cassandra: yes
Isolation for multi-record workSnapshot isolation in transactionsRead Committed default, SSI availableRepeatable Read defaultCockroachDB Serializable default
Change feedChange streamsLogical decodingBinlogCockroachDB changefeeds; DynamoDB Streams

Mechanics ​

WiredTiger: document-level concurrency, snapshots, checkpoints, journal, compression, cache Must-know ​

In plain words: WiredTiger is the storage engine under every modern MongoDB: it keeps versions of documents in memory so readers do not block writers, writes a consistent copy to disk every minute, logs every change in between, compresses data on disk, and uses its own cache plus the operating system's file cache.

Common misunderstanding: "Give the WiredTiger cache all the RAM." The filesystem cache holds the compressed on-disk pages and is also used; the manual says to avoid increasing the internal cache above its default. In containers set it explicitly, because "WiredTiger may not account for the memory limits of the specific container in certain cases."

Definition: "For most read and write operations, WiredTiger uses optimistic concurrency control. WiredTiger uses only intent locks at the global, database and collection levels. When the storage engine detects conflicts between two operations, one will incur a write conflict causing MongoDB to transparently retry that operation." Checkpoints: "MongoDB configures WiredTiger to create checkpoints, specifically, writing the snapshot data to disk at intervals of 60 seconds." The journal (write-ahead log) "persists all data modifications between checkpoints"; it is flushed "every 100 milliseconds" (storage.journal.commitIntervalMs) and on majority/j: true writes, in 100 MB files. Compression: "By default, WiredTiger uses Snappy block compression for all collections and prefix compression for all indexes"; zlib and zstd are options. Cache: the larger of 50% of (RAM − 1 GB) or 256 MB; "on a system with a total of 4GB of RAM the WiredTiger cache uses 1.5GB of RAM".

text
     t=0s checkpoint C1 on disk        t=30s crash                  restart
1    writes w1..w500 -> cache + journal (group commit every 100 ms)
2                                      process dies
3                                                                   open C1 (consistent at t=0)
4                                                                   replay journal w1..w500 -> state at crash
     -- without the journal, up to 60 s of writes since the last checkpoint would be lost

How write-ahead logs and checkpoints work in general is in Durability, WAL & Crash Recovery; MVCC in general is in MVCC, VACUUM & Bloat.

Knobs you will actually touch Important ​

KnobWhereDefaultWhen to change
storage.wiredTiger.engineConfig.cacheSizeGB / --wiredTigerCacheSizePctmongod.conf50% of (RAM − 1 GB), min 256 MBContainers; co-located processes
storage.wiredTiger.collectionConfig.blockCompressormongod.confsnappyzstd for better ratio on cold data
storage.journal.commitIntervalMsmongod.conf100Rarely
replication.oplogSizeMB / oplogMinRetentionHoursmongod.conf / replSetResizeOplog5% of disk (990 MB – 50 GB)Long maintenance windows, slow consumers
settings.electionTimeoutMillisreplica set config10000Flaky networks (raise)
members[n].priority, hidden, secondaryDelaySecs, votesreplica set config1, false, 0, 1DR members, analytics nodes
setDefaultRWConcernadmin commandw: "majority", read localCluster-wide policy
transactionLifetimeLimitSecondssetParameter60Never raise as a fix; shorten transactions
maxTransactionLockRequestTimeoutMillissetParametersmall (milliseconds)Brief DDL contention
slowms, profiler leveldb.setProfilingLevel()100 ms, level 0Diagnose slow queries
chunksizeconfig.settings128 MBHuge collections
allowDiskUse / allowDiskUseByDefaultper aggregate / setParametertrue by defaultStrict memory policies

Error codes you will catch Must-know ​

Code / nameMeaningRetry?
11000 DuplicateKey (E11000)Unique index violatedNo; treat as conflict or idempotent success
112 WriteConflictConcurrent write to the same document in a transactionYes, whole transaction (label TransientTransactionError)
251 NoSuchTransactionTransaction aborted/expiredYes, from the start
50 MaxTimeMSExpiredOperation hit maxTimeMSMaybe, after fixing the query
10107 NotWritablePrimary, 189 PrimarySteppedDown, 91 ShutdownInProgressFailover in progressYes (retryable writes do it once automatically)
64 WriteConcernFailed (wtimeout)Not replicated in time; write may still applyCheck before retrying; make writes idempotent
121 DocumentValidationFailure$jsonSchema rejected the writeNo; fix the data
10334 BSONObjectTooLarge, 17419Document over 16 MBNo; fix the schema
292 QueryExceededMemoryLimitNoDiskUseAllowedBlocking stage over 100 MB without disk useNo; add an index, $match earlier, or allow disk use
286 ChangeStreamHistoryLostResume token fell out of the oplogNo; resnapshot the consumer
13 Unauthorized, 18 AuthenticationFailedRBAC / credentialsNo

Operations ​

Schema validation with $jsonSchema Important ​

In plain words: you attach JSON Schema rules to a collection and the server rejects (or logs) writes that break them.

Common misunderstanding: "Turning validation on will break old documents." With validationLevel: "moderate" existing invalid documents are left alone unless updated; validationAction: "warn" only logs.

Definition: "By default, MongoDB rejects any insert or update operation that would produce an invalid document." validationLevel is strict (default, all inserts and updates) or moderate (only documents already valid); validationAction is error (default) or warn. Rejections return code 121 with a detailed errInfo. Change rules with collMod.

js
db.runCommand({
  collMod: "orders",
  validator: { $jsonSchema: {
    bsonType: "object",
    required: ["user_id", "status", "total_cents", "schema_version"],
    properties: {
      status: { enum: ["open", "paid", "closed"] },
      total_cents: { bsonType: "long", minimum: 0 },
      schema_version: { bsonType: "int" }
    }
  } },
  validationLevel: "moderate",
  validationAction: "error"
})

Security: SCRAM, x.509, RBAC, encryption at rest, field-level encryption Important ​

LayerMongoDB featureNote
AuthenticationSCRAM-SHA-256 (default), x.509 client certificates, LDAP/Kerberos/OIDC (Enterprise/Atlas)Enable with security.authorization: enabled; x.509 also for member auth (clusterAuthMode)
AuthorizationRBAC: built-in roles (read, readWrite, dbAdmin, clusterMonitor, backup) and custom rolesOne user per service, least privilege
In transitTLS (net.tls.mode: requireTLS)Also between replica set members
Encryption at restWiredTiger encrypted storage engine with KMIP or a local key file"Available in MongoDB Enterprise only"; always on in Atlas
Field-level encryptionClient-Side Field Level Encryption (CSFLE): driver encrypts fields before sending; deterministic for equality"no MongoDB product has access to your data in an unencrypted form"
Queryable EncryptionRandomised encryption with equality, range, prefix/suffix/substring queriesNewer alternative to CSFLE
AuditingAudit log (Enterprise/Atlas)DDL, auth, CRUD filters
InjectionOperator injection ({ "$ne": null } from user JSON)Validate types; the Laravel docs warn: "Do not pass unvalidated user input"

General threat model, roles and injection: Database Security; encryption choices: Encryption at Rest, in Transit & in Use.

Backups: mongodump, snapshots, PITR via the oplog Important ​

MethodHowRPO / restoreCaveats
mongodump / mongorestoreLogical BSON export; --oplog captures writes during the dump, --oplogReplay applies themPoint of dump end; slow restore (indexes rebuilt)Small data sets; for sharded clusters pause the balancer and DDL; not a sharded PITR tool
Filesystem snapshotsLVM/EBS snapshot with journal on the same volume, or fsyncLockSnapshot time; fast restoreMust be consistent across shards (stop balancer)
Hidden member for backupsDump or snapshot from a hidden secondaryNo load on serving membersWatch oplog window
PITR via oplogBase snapshot + continuous oplog capture, replay to a timestamp (--oplogLimit)SecondsRequires oplog retention covering the gap
Atlas Cloud Backup / Ops ManagerManaged snapshots + continuous PITRMinutes to secondsPaid; sharded-consistent

General backup design (RPO/RTO, testing restores): Backup, PITR & Disaster Recovery.

Performance tooling: profiler, mongostat, mongotop, Compass Good to know ​

ToolWhat it showsUse it to
Database profiler (db.setProfilingLevel(1, { slowms: 50 }))Slow operations in system.profile with plan summary, keys/docs examinedFind queries without indexes ("The profiler collects data for operations that exceed the slowms threshold")
Slow query logSame, in the mongod logAlways-on, low cost
explain("executionStats")Plan and work of one queryProve an index works
$indexStats, db.collection.stats(), $collStatsIndex usage, sizes, avgObjSizeRemove unused indexes, size the cache
mongostatPer-second inserts, queries, updates, dirty/used cache %Live capacity view
mongotopRead/write time per collectionFind the hot collection
db.currentOp() / killOpRunning operationsKill a runaway aggregation
rs.status(), rs.printSecondaryReplicationInfo()Member states, replication lagLag alerts
sh.status(), sh.balancerCollectionStatus()Chunks per shard, balancerSharding health
CompassGUI: schema analysis, visual explain, index suggestions, aggregation builderExploration and teaching
Atlas Performance Advisor / Query ProfilerSuggested indexes, slow query scatterManaged clusters

Observability in general: Database Observability.

Atlas features: Search, Vector Search, Flex (formerly serverless) Good to know ​

Atlas Search (now documented as MongoDB Search) is "an embedded full-text search" built on Lucene, queried with the $search stage as the first stage of an aggregation; indexes are separate from B-tree indexes and are eventually consistent with the collection. Vector Search stores embeddings in documents and queries them with $vectorSearch (approximate nearest neighbour), with pre-filters on indexed fields; it is the MongoDB answer to pgvector (Vector Search & pgvector). Serverless instances are gone: the Atlas docs state that "As of January 22, 2026, Atlas no longer supports M2 and M5 clusters and Serverless instances"; small and spiky workloads now use Flex clusters. Atlas also offers Online Archive, Data Federation and Charts. With Laravel MongoDB, searchIndex() and vectorSearchIndex() create these indexes from a migration.

Go ​

The official driver is go.mongodb.org/mongo-driver/v2 (module path from pkg.go.dev; this page builds against v2.10.1). Differences from database/sql: mongo.Connect(opts) returns a *mongo.Client that owns its pool and is shared process-wide; documents are bson.D (ordered; use it for commands, sorts and pipeline stages), bson.M (unordered) or structs with bson tags; IDs are bson.ObjectID; options are builders (options.Find().SetSort(...)); concerns are set on the client, database, collection or transaction. Every snippet below passes gofmt and go vet. A full service built on the driver is in MongoDB with Go.

Before ​

One orders document with an events array that every scan appends to, and a filter-plus-sort with no compound index behind it. Both are valid code; both degrade quietly as the data grows.

go
// Package main shows the anti-pattern: one order document that embeds an
// ever-growing events array, queried without a supporting index.
package main

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

type Event struct {
	Type string    `bson:"type"`
	At   time.Time `bson:"at"`
}

type Order struct {
	ID     bson.ObjectID `bson:"_id,omitempty"`
	UserID int64         `bson:"user_id"`
	Status string        `bson:"status"`
	Total  int64         `bson:"total_cents"`
	// Unbounded array: every status change, scan and webhook is appended here.
	// The document only ever grows, toward the 16 MiB BSON limit.
	Events []Event `bson:"events"`
}

func main() {
	ctx := context.Background()
	client, err := mongo.Connect(options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(ctx)

	orders := client.Database("shop").Collection("orders")

	// Each append rewrites a larger and larger document.
	_, err = orders.UpdateOne(ctx,
		bson.M{"_id": bson.NewObjectID()},
		bson.M{"$push": bson.M{"events": Event{Type: "scanned", At: time.Now()}}},
	)
	if err != nil {
		log.Fatal(err)
	}

	// No compound index: this is a collection scan plus an in-memory sort.
	cur, err := orders.Find(ctx,
		bson.M{"user_id": 42, "status": "open", "total_cents": bson.M{"$gte": 5000}},
		options.Find().SetSort(bson.D{{Key: "total_cents", Value: -1}}),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer cur.Close(ctx)
}

After ​

Events move to a bucket collection written with writeconcern.Majority(), the orders index follows ESR and is created with Indexes().CreateOne, and the aggregation starts with $match. Note the key order { user_id, status, total_cents, created_at }: this Before query sorts by total_cents, so total_cents is the Sort field here and created_at the Range; for the newest-first query in the ESR section the order is { user_id, status, created_at, total_cents }.

go
// Package main shows the bucket pattern, an ESR-ordered compound index, an
// aggregation that filters first, and a majority-acknowledged write.
package main

import (
	"context"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"go.mongodb.org/mongo-driver/v2/mongo/writeconcern"
)

const bucketSize = 200

func main() {
	ctx := context.Background()
	client, err := mongo.Connect(options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(ctx)

	db := client.Database("shop")
	orders := db.Collection("orders")

	// Events live in a separate collection, one document per bucket of at most
	// bucketSize events, so no single document can grow without bound.
	events := db.Collection("order_event_buckets",
		options.Collection().SetWriteConcern(writeconcern.Majority()))

	// ESR: equality (user_id, status), then sort (total_cents), then range
	// (created_at). The equality prefix keeps the sort served by the index.
	_, err = orders.Indexes().CreateOne(ctx, mongo.IndexModel{
		Keys: bson.D{
			{Key: "user_id", Value: 1},
			{Key: "status", Value: 1},
			{Key: "total_cents", Value: -1},
			{Key: "created_at", Value: 1},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	// Append to the newest non-full bucket, or open a new one (upsert).
	orderID := bson.NewObjectID()
	_, err = events.UpdateOne(ctx,
		bson.M{"order_id": orderID, "count": bson.M{"$lt": bucketSize}},
		bson.M{
			"$push": bson.M{"events": bson.M{"type": "scanned", "at": time.Now()}},
			"$inc":  bson.M{"count": 1},
		},
		options.UpdateOne().SetUpsert(true),
	)
	if err != nil {
		log.Fatal(err)
	}

	// $match first: the planner can use the index and later stages see few
	// documents.
	pipeline := mongo.Pipeline{
		{{Key: "$match", Value: bson.D{
			{Key: "user_id", Value: 42},
			{Key: "status", Value: "open"},
		}}},
		{{Key: "$group", Value: bson.D{
			{Key: "_id", Value: "$status"},
			{Key: "revenue", Value: bson.D{{Key: "$sum", Value: "$total_cents"}}},
		}}},
	}
	cur, err := orders.Aggregate(ctx, pipeline)
	if err != nil {
		log.Fatal(err)
	}
	defer cur.Close(ctx)
}

Consistency: concerns, read preference, causal session, transaction ​

SetRetryWrites, majority concerns on the client, readpref.SecondaryPreferred(readpref.WithMaxStaleness(90*time.Second)) for reports, a causally consistent session with mongo.NewSessionContext, and session.WithTransaction with readconcern.Snapshot(); the error switch uses mongo.ServerError's HasErrorLabel and HasErrorCode(112).

go
// Package main shows the consistency dials of the Go driver v2: retryable
// writes, majority write and read concerns, a secondary read preference with
// a staleness bound, a causally consistent session, and a multi-document
// transaction that the driver retries on TransientTransactionError.
package main

import (
	"context"
	"errors"
	"log"
	"os"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"go.mongodb.org/mongo-driver/v2/mongo/readconcern"
	"go.mongodb.org/mongo-driver/v2/mongo/readpref"
	"go.mongodb.org/mongo-driver/v2/mongo/writeconcern"
)

func main() {
	uri := os.Getenv("MONGODB_URI") // e.g. mongodb://localhost:27017/?replicaSet=rs0
	if uri == "" {
		log.Println("MONGODB_URI not set; nothing to do")
		return
	}
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// Client-wide defaults. Retryable writes are on by default in current
	// drivers; setting them explicitly documents the intent.
	client, err := mongo.Connect(options.Client().
		ApplyURI(uri).
		SetRetryWrites(true).
		SetWriteConcern(writeconcern.Majority()).
		SetReadConcern(readconcern.Majority()).
		SetTimeout(5 * time.Second))
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = client.Disconnect(context.Background()) }()

	db := client.Database("shop")

	// Reads that tolerate lag: secondaries first, but never one more than 90
	// seconds behind the primary (90 s is the smallest maxStalenessSeconds).
	reports := db.Collection("orders", options.Collection().
		SetReadPreference(readpref.SecondaryPreferred(readpref.WithMaxStaleness(90*time.Second))))
	if _, err := reports.CountDocuments(ctx, bson.D{{Key: "status", Value: "open"}}); err != nil {
		log.Println("report:", err)
	}

	// Causal consistency: inside one session, a read after a majority write
	// observes that write even when it is served by a secondary.
	sess, err := client.StartSession(options.Session().SetCausalConsistency(true))
	if err != nil {
		log.Fatal(err)
	}
	defer sess.EndSession(context.Background())

	profiles := db.Collection("profiles", options.Collection().
		SetReadPreference(readpref.Secondary()))
	sctx := mongo.NewSessionContext(ctx, sess)
	if _, err := profiles.UpdateOne(sctx,
		bson.D{{Key: "_id", Value: 42}},
		bson.D{{Key: "$set", Value: bson.D{{Key: "name", Value: "Sara"}}}},
		options.UpdateOne().SetUpsert(true)); err != nil {
		log.Fatal(err)
	}
	var p bson.M
	if err := profiles.FindOne(sctx, bson.D{{Key: "_id", Value: 42}}).Decode(&p); err != nil &&
		!errors.Is(err, mongo.ErrNoDocuments) {
		log.Fatal(err)
	}

	// Multi-document transaction: move stock to a reservation atomically.
	// WithTransaction retries the callback on TransientTransactionError and
	// the commit on UnknownTransactionCommitResult (up to 120 seconds), so the
	// callback must be safe to run more than once.
	txnOpts := options.Transaction().
		SetReadConcern(readconcern.Snapshot()).
		SetWriteConcern(writeconcern.Majority())
	_, err = sess.WithTransaction(ctx, func(tctx context.Context) (any, error) {
		stock := db.Collection("stock")
		res, err := stock.UpdateOne(tctx,
			bson.D{{Key: "sku", Value: "A-1"}, {Key: "qty", Value: bson.D{{Key: "$gte", Value: 1}}}},
			bson.D{{Key: "$inc", Value: bson.D{{Key: "qty", Value: -1}}}})
		if err != nil {
			return nil, err
		}
		if res.MatchedCount == 0 {
			return nil, errors.New("out of stock") // aborts, not retried
		}
		_, err = db.Collection("reservations").InsertOne(tctx,
			bson.D{{Key: "sku", Value: "A-1"}, {Key: "order_id", Value: bson.NewObjectID()}})
		return nil, err
	}, txnOpts)

	// Inspect what came back. WriteConflict is code 112; the label tells you
	// whether a retry of the whole transaction is safe.
	var se mongo.ServerError
	switch {
	case err == nil:
		log.Println("reserved")
	case errors.As(err, &se) && se.HasErrorLabel("TransientTransactionError"):
		log.Println("transient, retry budget exhausted:", err)
	case errors.As(err, &se) && se.HasErrorCode(112):
		log.Println("write conflict:", err)
	default:
		log.Println("transaction failed:", err)
	}
}

Operations: validator, index types, explain, change stream ​

CreateCollection with SetValidator, CreateMany with partial, sparse, text and wildcard indexes, a TTL index via SetExpireAfterSeconds, 2dsphere and hashed indexes, an explain command through RunCommand (the driver has no explain helper), and a change stream with SetFullDocument(options.UpdateLookup) and SetResumeAfter.

go
// Package main shows the operational side with the Go driver v2: a
// $jsonSchema validator, TTL / partial / sparse / 2dsphere / text / wildcard /
// hashed indexes, an explain of an ESR query, and a resumable change stream.
package main

import (
	"context"
	"log"
	"os"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	uri := os.Getenv("MONGODB_URI")
	if uri == "" {
		log.Println("MONGODB_URI not set; nothing to do")
		return
	}
	ctx := context.Background()
	client, err := mongo.Connect(options.Client().ApplyURI(uri))
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = client.Disconnect(ctx) }()
	db := client.Database("shop")

	// Schema validation: required fields and types, enforced by the server.
	// validationLevel "moderate" leaves existing invalid documents alone.
	schema := bson.D{{Key: "$jsonSchema", Value: bson.D{
		{Key: "bsonType", Value: "object"},
		{Key: "required", Value: bson.A{"user_id", "status", "total_cents", "schema_version"}},
		{Key: "properties", Value: bson.D{
			{Key: "user_id", Value: bson.D{{Key: "bsonType", Value: "long"}}},
			{Key: "status", Value: bson.D{{Key: "enum", Value: bson.A{"open", "paid", "closed"}}}},
			{Key: "total_cents", Value: bson.D{{Key: "bsonType", Value: "long"}, {Key: "minimum", Value: 0}}},
			{Key: "schema_version", Value: bson.D{{Key: "bsonType", Value: "int"}}},
		}},
	}}}
	err = db.CreateCollection(ctx, "orders", options.CreateCollection().
		SetValidator(schema).
		SetValidationLevel("strict").
		SetValidationAction("error"))
	if err != nil {
		log.Println("create orders (may already exist):", err)
	}
	orders := db.Collection("orders")

	_, err = orders.Indexes().CreateMany(ctx, []mongo.IndexModel{
		// ESR compound index: Equality, Sort, Range.
		{Keys: bson.D{{Key: "user_id", Value: 1}, {Key: "status", Value: 1}, {Key: "created_at", Value: -1}, {Key: "total_cents", Value: 1}}},
		// Partial: only open orders are indexed, so the index stays small.
		{
			Keys:    bson.D{{Key: "created_at", Value: 1}},
			Options: options.Index().SetPartialFilterExpression(bson.D{{Key: "status", Value: "open"}}).SetName("open_by_created"),
		},
		// Sparse + unique: only documents that have a coupon_code are indexed.
		{Keys: bson.D{{Key: "coupon_code", Value: 1}}, Options: options.Index().SetSparse(true).SetUnique(true)},
		// Text index for keyword search on notes.
		{Keys: bson.D{{Key: "notes", Value: "text"}}},
		// Wildcard index over a free-form attributes subdocument.
		{Keys: bson.D{{Key: "attrs.$**", Value: 1}}},
	})
	if err != nil {
		log.Fatal(err)
	}

	// TTL: the TTL monitor deletes a session about an hour after last_seen.
	_, err = db.Collection("sessions").Indexes().CreateOne(ctx, mongo.IndexModel{
		Keys:    bson.D{{Key: "last_seen", Value: 1}},
		Options: options.Index().SetExpireAfterSeconds(3600),
	})
	if err != nil {
		log.Fatal(err)
	}

	// 2dsphere for GeoJSON points, hashed for an even shard-key spread.
	_, err = db.Collection("stores").Indexes().CreateMany(ctx, []mongo.IndexModel{
		{Keys: bson.D{{Key: "location", Value: "2dsphere"}}},
		{Keys: bson.D{{Key: "tenant_id", Value: "hashed"}}},
	})
	if err != nil {
		log.Fatal(err)
	}

	// explain: the driver has no helper, so run the explain command. Look at
	// queryPlanner.winningPlan (IXSCAN vs COLLSCAN, a SORT stage or not) and
	// executionStats (nReturned vs totalKeysExamined vs totalDocsExamined).
	explain := bson.D{
		{Key: "explain", Value: bson.D{
			{Key: "find", Value: "orders"},
			{Key: "filter", Value: bson.D{
				{Key: "user_id", Value: int64(42)},
				{Key: "status", Value: "open"},
				{Key: "total_cents", Value: bson.D{{Key: "$gte", Value: 5000}}},
			}},
			{Key: "sort", Value: bson.D{{Key: "created_at", Value: -1}}},
		}},
		{Key: "verbosity", Value: "executionStats"},
	}
	var plan bson.M
	if err := db.RunCommand(ctx, explain).Decode(&plan); err != nil {
		log.Fatal(err)
	}
	log.Println("queryPlanner:", plan["queryPlanner"])

	// Change stream with a resume token: persist the token after each event
	// and pass it back with SetResumeAfter after a restart.
	var lastToken bson.Raw // load from durable storage in a real consumer
	csOpts := options.ChangeStream().SetFullDocument(options.UpdateLookup)
	if lastToken != nil {
		csOpts.SetResumeAfter(lastToken)
	}
	pipeline := mongo.Pipeline{
		{{Key: "$match", Value: bson.D{{Key: "operationType", Value: bson.D{{Key: "$in", Value: bson.A{"insert", "update"}}}}}}},
	}
	wctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()
	stream, err := orders.Watch(wctx, pipeline, csOpts)
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = stream.Close(ctx) }()
	for stream.Next(wctx) {
		var ev struct {
			OperationType string `bson:"operationType"`
			FullDocument  bson.M `bson:"fullDocument"`
		}
		if err := stream.Decode(&ev); err != nil {
			log.Fatal(err)
		}
		log.Println(ev.OperationType, ev.FullDocument["_id"])
		lastToken = stream.ResumeToken() // save it before acknowledging work
	}
	if err := stream.Err(); err != nil && wctx.Err() == nil {
		log.Fatal(err)
	}
}

Laravel ​

MongoDB support comes from the official mongodb/laravel-mongodb package (docs at mongodb.com/docs/drivers/php/laravel-mongodb). Models extend MongoDB\Laravel\Eloquent\Model; the primary key is _id exposed as id; the schema builder's Blueprint adds index() with options, unique(), sparse(), expire() (TTL), geospatial(), jsonSchema() (5.5+), searchIndex() and vectorSearchIndex(); the query builder adds readPreference(), options() and raw() (which hands a closure the PHP library's MongoDB\Collection). Transactions use the usual facade, DB::transaction(fn () => ..., attempts: 3), and the package documents the limits: no transactions on standalone deployments, nested transactions raise RuntimeException, and RefreshDatabase/DatabaseTransactions are unsupported in tests. Eloquent hazards that carry over (N+1 via $lookup-backed relations, lazy loading) are in ORM Pitfalls.

Before ​

An Eloquent model on the mongodb connection that calls push() on an array that is never trimmed, plus a filtered, sorted query with no index.

php
<?php

// app/Models/Order.php — one document per order, events embedded forever.
namespace App\Models;

use MongoDB\Laravel\Eloquent\Model;

class Order extends Model
{
    protected $connection = 'mongodb';
    protected $fillable = ['user_id', 'status', 'total_cents', 'events'];
}

// app/Services/OrderTracker.php
namespace App\Services;

use App\Models\Order;

final class OrderTracker
{
    public function record(Order $order, string $type): void
    {
        // $push on an array that is never trimmed: the document only grows
        // toward the 16 MiB BSON limit, and every append rewrites it.
        $order->push('events', ['type' => $type, 'at' => now()->toIso8601String()]);
    }

    public function openOrders(int $userId)
    {
        // No compound index behind this filter and sort: collection scan plus
        // an in-memory sort.
        return Order::where('user_id', $userId)
            ->where('status', 'open')
            ->where('total_cents', '>=', 5000)
            ->orderBy('total_cents', 'desc')
            ->get();
    }
}

After ​

The migration declares the ESR-ordered compound index; the model and service implement the bucket pattern, an aggregation with $match first, and a multi-document transaction. As in Go, the index is ESR for the Before query (sort by total_cents), not for the newest-first query of the ESR section.

php
<?php

// database/migrations/2026_01_01_000000_create_order_event_buckets.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
use MongoDB\Laravel\Schema\Blueprint;

return new class extends Migration
{
    protected $connection = 'mongodb';

    public function up(): void
    {
        Schema::create('order_event_buckets', function (Blueprint $collection) {
            $collection->index('order_id');
        });

        // ESR order: equality (user_id, status), sort (total_cents), range
        // (created_at). Direction per key is given as 1 or -1.
        Schema::create('orders', function (Blueprint $collection) {
            $collection->index([
                'user_id' => 1,
                'status' => 1,
                'total_cents' => -1,
                'created_at' => 1,
            ]);
        });
    }

    public function down(): void
    {
        Schema::drop('order_event_buckets');
        Schema::drop('orders');
    }
};
php
<?php

// app/Models/OrderEventBucket.php — bucket pattern: bounded events per document.
namespace App\Models;

use MongoDB\Laravel\Eloquent\Model;

class OrderEventBucket extends Model
{
    protected $connection = 'mongodb';

    protected $fillable = ['order_id', 'count', 'events'];

    public const MAX_EVENTS = 200;
}

// app/Services/OrderTracker.php
namespace App\Services;

use App\Models\Order;
use App\Models\OrderEventBucket;
use Illuminate\Support\Facades\DB;

final class OrderTracker
{
    public function record(Order $order, string $type): void
    {
        // Append to a bucket that still has room; open a new one otherwise.
        $bucket = OrderEventBucket::where('order_id', $order->getKey())
            ->where('count', '<', OrderEventBucket::MAX_EVENTS)
            ->first() ?? new OrderEventBucket([
                'order_id' => $order->getKey(),
                'count' => 0,
                'events' => [],
            ]);

        // push() and increment() are atomic updates keyed by _id, so a brand-new
        // bucket must be persisted first or the update matches nothing.
        if (! $bucket->exists) {
            $bucket->save();
        }

        $bucket->push('events', ['type' => $type, 'at' => now()->toIso8601String()]);
        $bucket->increment('count');
    }

    public function revenueByStatus(int $userId): array
    {
        // Raw aggregation with $match first so the index above is used.
        $cursor = DB::connection('mongodb')
            ->table('orders')
            ->raw(fn ($collection) => $collection->aggregate([
                ['$match' => ['user_id' => $userId, 'status' => 'open']],
                ['$group' => ['_id' => '$status', 'revenue' => ['$sum' => '$total_cents']]],
            ]));

        return iterator_to_array($cursor, false);
    }

    public function closeOrder(Order $order, int $refundCents): void
    {
        // Needs a replica set or sharded cluster; the callback commits or
        // rolls back as one multi-document transaction.
        DB::connection('mongodb')->transaction(function () use ($order, $refundCents) {
            $order->update(['status' => 'closed']);
            OrderEventBucket::create([
                'order_id' => $order->getKey(),
                'count' => 1,
                'events' => [['type' => 'closed', 'refund_cents' => $refundCents]],
            ]);
        }, attempts: 3);
    }
}

Validation and index types in a migration ​

jsonSchema() with validationLevel: 'moderate', a named unique index, expire() for TTL, geospatial(..., '2dsphere'), sparse(), and a partial index through index(..., options: ['partialFilterExpression' => ...]).

php
<?php

// database/migrations/2026_01_02_000000_create_orders_validation_and_indexes.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
use MongoDB\Laravel\Schema\Blueprint;

return new class extends Migration
{
    protected $connection = 'mongodb';

    public function up(): void
    {
        // Server-side $jsonSchema validation (Laravel MongoDB 5.5+).
        Schema::create('invoices', function (Blueprint $collection) {
            $collection->jsonSchema(
                schema: [
                    'bsonType' => 'object',
                    'required' => ['order_id', 'amount_cents', 'schema_version'],
                    'properties' => [
                        // PHP ints that fit in 32 bits are sent as BSON int, larger ones as long.
                        'amount_cents' => ['bsonType' => ['int', 'long'], 'minimum' => 0],
                        'schema_version' => ['bsonType' => 'int'],
                    ],
                ],
                validationLevel: 'moderate',
                validationAction: 'error',
            );
            $collection->unique('order_id', options: ['name' => 'invoice_order_unique']);
        });

        Schema::create('sessions_mongo', function (Blueprint $collection) {
            // TTL: expireAfterSeconds = 3600 on last_seen.
            $collection->expire('last_seen', 3600);
        });

        Schema::create('stores', function (Blueprint $collection) {
            // 2dsphere for GeoJSON points; sparse for an optional field.
            $collection->geospatial('location', '2dsphere');
            $collection->sparse('franchise_code');
            // Partial index: only open tickets are indexed. Options are passed
            // through to createIndexes unchanged.
            $collection->index(
                ['created_at' => 1],
                name: 'open_tickets_by_created',
                options: ['partialFilterExpression' => ['status' => 'open']],
            );
        });
    }

    public function down(): void
    {
        Schema::drop('invoices');
        Schema::drop('sessions_mongo');
        Schema::drop('stores');
    }
};

Read preference and a change-stream consumer ​

A dashboard query with ->readPreference(ReadPreference::SECONDARY_PREFERRED), and an Artisan command that tails a change stream through raw() and MongoDB\Collection::watch(), storing the resume token after each processed event.

php
<?php

// app/Services/OrderReads.php — read preference per query.
namespace App\Services;

use Illuminate\Support\Facades\DB;
use MongoDB\Driver\ReadPreference;

final class OrderReads
{
    public function openCountForDashboard(): int
    {
        // Dashboards tolerate lag: read from a secondary when one is available.
        return DB::connection('mongodb')
            ->table('orders')
            ->where('status', 'open')
            ->readPreference(ReadPreference::SECONDARY_PREFERRED)
            ->count();
    }

    public function orderForCheckout(string $id): ?object
    {
        // Read-your-writes path: default primary read preference.
        return DB::connection('mongodb')->table('orders')->where('id', $id)->first();
    }
}

// app/Console/Commands/ProjectOrders.php — change stream consumer.
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

final class ProjectOrders extends Command
{
    protected $signature = 'orders:project';

    protected $description = 'Tail the orders change stream and update a read model';

    public function handle(): int
    {
        $token = Cache::get('orders:resume_token');

        $options = ['fullDocument' => 'updateLookup'];
        if ($token !== null) {
            $options['resumeAfter'] = $token;
        }

        // raw() hands the closure the PHP library's MongoDB\Collection;
        // watch() returns a MongoDB\ChangeStream iterator.
        $stream = DB::connection('mongodb')
            ->table('orders')
            ->raw(fn ($collection) => $collection->watch(
                [['$match' => ['operationType' => ['$in' => ['insert', 'update']]]]],
                $options,
            ));

        for ($stream->rewind(); true; $stream->next()) {
            if (! $stream->valid()) {
                continue; // no event in this await period; keep polling
            }
            $event = $stream->current();
            $this->info($event['operationType'].' '.(string) $event['documentKey']['_id']);

            // Persist the token after the side effect so a crash replays,
            // never skips (consumers must be idempotent).
            Cache::forever('orders:resume_token', $stream->getResumeToken());
        }
    }
}

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Lost update on a counter or stockAtomic update operatorsupdateOne({ _id, qty: { $gte: n } }, { $inc: { qty: -n } })No transaction, no raceOnly for single-document invariants
Read-modify-write of a whole documentOptimistic concurrencyversion field in the filter, $inc: {version: 1}; 0 matched = conflictWorks across requestsClient retry loop
Exactly one document per business keyUnique index + upsertupdateOne({email}, {$setOnInsert: ...}, {upsert: true})IdempotentConcurrent upserts may raise E11000: retry once
Paging a large feedKeyset paginationfind({ created_at: { $lt: last } }).sort({ created_at: -1 }).limit(20) on an indexConstant cost per pageNo "jump to page 500"; see Pagination
Hot document under heavy writesSplit counterN sub-documents or N documents {_id: "c:7:shard3"}, sum on readSpreads write locksReads aggregate N values
Two documents must change togetherTransaction or redesignWithTransaction; or embed both into one documentAtomicCost, 60 s limit, WriteConflict retries
Duplicate processing of eventsIdempotency keyUnique index on event_id in a processed collectionSafe redeliveryStorage for keys (TTL index to expire)

Lost update ​

text
     Request A (buy 1)                               Request B (buy 1)          -- stock: 1
1    findOne({sku: "A-1"}) -> qty 1
2                                                    findOne({sku: "A-1"}) -> qty 1
3    updateOne({sku: "A-1"}, {$set: {qty: 0}})
4                                                    updateOne({sku: "A-1"}, {$set: {qty: 0}})
     -- two orders, one item. Fix: one conditional $inc; the second matches 0 documents
js
// mongosh: atomic, conditional decrement
db.stock.updateOne({ sku: "A-1", qty: { $gte: 1 } }, { $inc: { qty: -1 } })
// { matchedCount: 0 } for the loser -> "sold out"
go
// Go (excerpt of the vetted consistency snippet): matched 0 means the condition failed
res, err := stock.UpdateOne(tctx,
	bson.D{{Key: "sku", Value: "A-1"}, {Key: "qty", Value: bson.D{{Key: "$gte", Value: 1}}}},
	bson.D{{Key: "$inc", Value: bson.D{{Key: "qty", Value: -1}}}})
php
// Laravel MongoDB: decrement() issues one $inc; the where() makes it conditional
$updated = DB::connection('mongodb')->table('stock')
    ->where('sku', 'A-1')
    ->where('qty', '>=', 1)
    ->decrement('qty');
if ($updated === 0) {
    throw new \RuntimeException('Sold out');
}

Idempotent upsert by business key ​

js
db.users.createIndex({ email: 1 }, { unique: true })
db.users.updateOne(
  { email: "a@example.com" },
  { $setOnInsert: { created_at: new Date() }, $set: { last_login: new Date() } },
  { upsert: true }
)
// two concurrent first logins: one may fail with E11000 -> retry once, it then matches
php
// Laravel MongoDB (v4.7+): query-builder upsert() keyed by the unique field;
// the third argument lists the fields to update when the document exists.
$affected = DB::connection('mongodb')->table('users')->upsert(
    [['email' => $email, 'last_login' => now()]],
    'email',
    'last_login',
);

Retries and failure handling ​

SituationWhat the driver doesWhat you do
Primary steps down during a single writeRetryable writes resend onceNothing, if retryWrites is on (default)
Network error during a readRetryable reads retry onceNothing
Transaction TransientTransactionErrorWithTransaction / Laravel attempts re-run the callbackKeep the callback idempotent
UnknownTransactionCommitResultWithTransaction retries the commitNothing
wtimeout / WriteConcernFailedReturns error; write may still applyRe-read before retrying; idempotent writes
E11000 on concurrent upsertReturns errorRetry once; it will match
Election in progress (about 12 s median)Server selection waits up to serverSelectionTimeoutMS (30 s)Set client timeouts above election time; surface 503 after that

Rules: retries are only safe for idempotent operations ($set, conditional $inc, upserts by key); never wrap emails or payments inside a retried callback; put a deadline on the whole operation (Go SetTimeout / context.WithTimeout, Laravel attempts).

Choosing: MongoDB or PostgreSQL jsonb ​

PostgreSQL's jsonb gives you documents inside a relational database: binary JSON, GIN indexes, containment queries and full transactions, joined to normal tables. MongoDB gives you documents as the primary model plus built-in replication and sharding.

sql
-- PostgreSQL: the same "order with lines" as a jsonb column next to relational columns
CREATE TABLE orders (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id     bigint NOT NULL,
  status      text   NOT NULL CHECK (status IN ('open','paid','closed')),
  created_at  timestamptz NOT NULL DEFAULT now(),
  doc         jsonb  NOT NULL            -- lines, address, free-form attributes
);
CREATE INDEX orders_user_status_created ON orders (user_id, status, created_at DESC); -- ESR in SQL
CREATE INDEX orders_doc_gin ON orders USING gin (doc jsonb_path_ops);
SELECT id FROM orders WHERE doc @> '{"lines": [{"sku": "A-1"}]}';                     -- containment via GIN
UPDATE orders SET doc = jsonb_set(doc, '{address,city}', '"Berlin"') WHERE id = 42;     -- rewrites the row
Workload or constraintChooseExtra techniqueReason
Aggregate-shaped reads (order + lines, profile + settings), evolving shapeMongoDBEmbedding, schema versioning, $jsonSchemaOne document read, one atomic write
Mostly relational data with a few flexible attributesPostgreSQL jsonbGIN index on the jsonb column, generated columns for hot keysJoins, constraints and SQL stay available
Cross-entity invariants on every request (ledgers, double-entry)PostgreSQLSerializable or FOR UPDATETransactions are the normal path, not the exception
Write scale beyond one primary, multi-regionMongoDB sharding (or distributed SQL)Shard key + zonesNative balancer and routing
Ad-hoc analytics and BI joinsPostgreSQL or a warehouseChange streams/CDC into the warehouse$lookup is not a planner-driven join engine
Time series and event bucketsMongoDB time series / bucket pattern, or TimescaleDBTTL indexesBoth fine; pick what the team runs
Full-text plus vector plus operational data in one placeMongoDB Atlas (Search, Vector Search) or PostgreSQL (FTS + pgvector)—See Full-Text Search and Vector Search
Team knows SQL, data under a few TB, one regionPostgreSQLjsonb where neededFewer moving parts

The rule of thumb: if you can write down your top ten queries and each one reads one aggregate by its key, MongoDB fits; if they join across five entities and the list keeps changing, start relational. Families overview: NoSQL: Families & Data Models.

In architecture: from a single process to a distributed system ​

MongoDB's atomic unit is one document on one replica set. Everything in this section is about what happens when a business operation needs more than that.

Monolith: one process, one database ​

How it shows up: one Laravel or Go app, one replica set (never a standalone in production: transactions and change streams need a replica set). Collections map to aggregates.

Simplest correct usage: embed child data that is read together, conditional $inc/$set for invariants inside a document, w: "majority" (the default), primary reads, and ESR indexes confirmed by explain.

Example (simple): a shop's orders document embeds its lines and shipping address; checkout is one insertOne, and stock is a conditional $inc on products. No transaction.

Example (complex): a booking system where a reservation must both decrement seat availability and create a booking document. Either embed the bookings in the flight's seat-map document (bounded: one flight has at most 400 seats) so it stays one atomic update, or use WithTransaction with retries and keep it under a few milliseconds.

Modular monolith and multiple databases ​

How it shows up: modules own collections (and ideally separate databases on the same cluster). A transaction can still span them on one replica set, but that couples modules.

Example: Billing and Catalog in one cluster with separate databases and separate users (RBAC roles scoped per database). Billing keeps an extended reference of product name and price at order time instead of reading Catalog's collections. Cross-module reactions go through change streams on each module's own collection, not through shared reads.

Microservices: one cluster per service, events between them ​

What survives: each service's single-document atomicity and local transactions. What does not: atomicity across services. Use the outbox: write the business change and an outbox document in one transaction (or embed the pending event inside the aggregate document, which needs no transaction), and relay it with a change stream.

text
Order service (MongoDB)                    Relay                     Payment service
1  WithTransaction: insert order(PENDING) + insert outbox{OrderCreated}
2                                          change stream on outbox -> publish to Kafka; save resume token
3                                                                    consume OrderCreated (dedup by event_id unique index)
4                                                                    charge; emit PaymentCaptured
5  consume PaymentCaptured -> updateOne({_id, status: "PENDING"}, {$set: {status: "PAID"}})
   -- the status filter in 5 is a semantic lock: a cancelled order is not resurrected

Details: Transactional Outbox, Saga Pattern, Idempotent Consumers.

Distributed data: replicas, caches, sharded and multi-region ​

Replica lag: secondary reads are stale by the replication lag; use causal sessions with majority concerns for read-your-writes, or keep those reads on the primary. Caches: invalidate from a change stream after commit rather than in the request; a cache write racing an invalidation can resurrect stale data. Sharded clusters: transactions across shards use two-phase commit internally and cost more; keep each invariant inside one shard-key value (e.g. everything of one tenant). Multi-region: place voting members across three regions so a region loss keeps a majority; use tag-aware write concern for cross-region durability and nearest with tags for local reads; zones pin data residency. Replication theory: Replication & Failover; consistency models: Eventual Consistency.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesMongoDB consequence
1× (one replica set, working set fits in cache)Indexes by ESR, embedding, defaultsexplain every new query; watch mongostat dirty/used cache
10× (hot collections, cache misses, read-heavy dashboards)Bucket/subset patterns, computed fields, secondaryPreferred for reports, hidden analytics member, bigger instancesDrop unnecessary indexes; profiler at 50 ms; connection pool sizing per app instance
100× (write rate beyond one primary, multi-region)Shard with a compound or hashed key, zones per region, $merge materialised viewsEvery hot query must contain the shard key; plan resharding capacity; per-shard backups with PITR

Lab ​

Everything runs locally with Docker; expected output shapes are in comments (counts and timings will differ).

Setup: a three-member replica set.

bash
docker network create mongo-lab
for i in 1 2 3; do
  docker run -d --name m$i --net mongo-lab mongo:8.0 --replSet rs0 --bind_ip_all
done
docker exec -it m1 mongosh --eval 'rs.initiate({_id: "rs0", members: [
  {_id: 0, host: "m1:27017", priority: 2},
  {_id: 1, host: "m2:27017"},
  {_id: 2, host: "m3:27017"}]})'
docker exec -it m1 mongosh --eval 'rs.status().members.map(m => m.name + " " + m.stateStr)'
# [ 'm1:27017 PRIMARY', 'm2:27017 SECONDARY', 'm3:27017 SECONDARY' ]

Experiment 1: write concern and a lagging majority.

bash
# stop two secondaries: a majority (2 of 3) is impossible
docker stop m2 m3
docker exec -it m1 mongosh --eval '
  db.getSiblingDB("lab").t.insertOne({x: 1}, {writeConcern: {w: 1}});                         // acknowledged at once
  try { db.getSiblingDB("lab").t.insertOne({x: 2}, {writeConcern: {w: "majority", wtimeout: 3000}}) }
  catch (e) { print(e.codeName) }'                                                            // WriteConcernFailed after 3 s
# after ~10 s m1 steps down (it cannot see a majority): further writes fail with NotWritablePrimary
docker start m2 m3

Experiment 2: election and failover.

bash
docker stop m1
sleep 15; docker exec -it m2 mongosh --eval 'rs.status().members.map(m => m.name + " " + m.stateStr)'
# [ 'm1:27017 (not reachable/healthy)', 'm2:27017 PRIMARY', 'm3:27017 SECONDARY' ]  -- or m3 PRIMARY
docker start m1
# m1 rejoins as SECONDARY, then (priority 2) calls an election and becomes PRIMARY again

Experiment 3: ESR index and explain.

js
// docker exec -it m1 mongosh lab
for (let i = 0; i < 200000; i++) db.orders.insertOne({ user_id: i % 1000, status: i % 3 ? "open" : "paid",
  total_cents: i % 10000, created_at: new Date(Date.now() - i * 1000) })
const q = { user_id: 42, status: "open", total_cents: { $gte: 5000 } }
db.orders.find(q).sort({ created_at: -1 }).limit(20).explain("executionStats").queryPlanner.winningPlan
// stage: 'SORT' over 'COLLSCAN' -> totalKeysExamined: 0, totalDocsExamined: 200000
db.orders.createIndex({ user_id: 1, status: 1, total_cents: 1, created_at: -1 })  // E E R S
// winningPlan: FETCH -> SORT -> IXSCAN (E E R S): in-memory sort, totalKeysExamined: 66
db.orders.createIndex({ user_id: 1, status: 1, created_at: -1, total_cents: 1 })  // E E S R
db.orders.find(q).sort({ created_at: -1 }).limit(20).explain("executionStats")
// winningPlan: LIMIT -> FETCH -> IXSCAN on user_id_1_status_1_created_at_-1_total_cents_1, no SORT
// totalKeysExamined: 40, totalDocsExamined: 20; rejectedPlans has 1 entry (the E E R S index)

Experiment 4: shard a collection.

bash
# config server replica set, two single-member shard replica sets, one mongos
docker run -d --name cfg --net mongo-lab mongo:8.0 --configsvr --replSet cfgrs --port 27019 --bind_ip_all
docker run -d --name sh1 --net mongo-lab mongo:8.0 --shardsvr --replSet sh1 --port 27018 --bind_ip_all
docker run -d --name sh2 --net mongo-lab mongo:8.0 --shardsvr --replSet sh2 --port 27018 --bind_ip_all
docker exec cfg mongosh --port 27019 --eval 'rs.initiate({_id: "cfgrs", configsvr: true, members: [{_id: 0, host: "cfg:27019"}]})'
docker exec sh1 mongosh --port 27018 --eval 'rs.initiate({_id: "sh1", members: [{_id: 0, host: "sh1:27018"}]})'
docker exec sh2 mongosh --port 27018 --eval 'rs.initiate({_id: "sh2", members: [{_id: 0, host: "sh2:27018"}]})'
docker run -d --name mongos --net mongo-lab -p 27017:27017 mongo:8.0 mongos --configdb cfgrs/cfg:27019 --bind_ip_all
docker exec -it mongos mongosh --eval '
  sh.addShard("sh1/sh1:27018"); sh.addShard("sh2/sh2:27018");
  sh.shardCollection("lab.events", { device_id: "hashed" });
  for (let i = 0; i < 50000; i++) db.getSiblingDB("lab").events.insertOne({ device_id: i, v: i });
  db.getSiblingDB("lab").events.getShardDistribution()'
# Shard sh1 ... docs: 24602 / Shard sh2 ... docs: 25398   (lab run; yours will differ slightly)
docker exec -it mongos mongosh lab --eval 'db.events.find({device_id: 7}).explain().queryPlanner.winningPlan.stage'
# SINGLE_SHARD   (targeted)
docker exec -it mongos mongosh lab --eval 'db.events.find({v: 7}).explain().queryPlanner.winningPlan.stage'
# SHARD_MERGE    (broadcast)

Experiment 5: transaction WriteConflict. In two mongosh sessions on the replica set, start a session and transaction in each (s = db.getMongo().startSession(); s.startTransaction()), update the same document in session A, then in session B: B fails with WriteConflict and the error carries errorLabels: [ 'TransientTransactionError' ]. Commit A; retry B from the start.

In production systems ​

  • The 16 MB ceiling is documented and hard. The Documents page states it, and the Avoid Unbounded Arrays anti-pattern page recommends the subset pattern and references as the repair.
  • The default global write concern is majority, except for the documented arbiter edge case where it falls back to { w: 1 }; check db.adminCommand({ getDefaultRWConcern: 1 }) on PSA sets.
  • Transactions have documented limits: under one minute by default (transactionLifetimeLimitSeconds), aborted under cache pressure with a write conflict, and unavailable on standalone deployments (also stated by the Laravel package docs).
  • Serverless instances no longer exist in Atlas (retired 22 January 2026 per the Atlas Flex migration page); architecture diagrams that still show them are out of date.

Common misconceptions ​

BeliefReality
"Schemaless means no schema."The schema lives in code and queries; enforce it with $jsonSchema, unique indexes and schema_version.
"MongoDB has no transactions."Single-document writes are atomic; multi-document transactions exist on replica sets (FCV 4.0) and sharded clusters (FCV 4.2).
"j: true means the write survives anything."It survives a primary restart; only w: "majority" survives failover.
"Reading from secondaries is free read scaling."Secondaries replay every write, lag, and miss your own recent writes.
"ObjectId is a fine ranged shard key."It increases monotonically: all inserts hit one chunk. Hash it or use a compound key.
"An IXSCAN in explain means the query is efficient."Check totalKeysExamined vs nReturned and the absence of a SORT stage.
"More indexes, faster database."Each index costs cache, disk and write work; unnecessary indexes are a named anti-pattern.
"An arbiter gives me the same safety as a third data node."It votes but holds no data; with one data node down, majority writes stall.
"Change streams are a durable queue."They are bounded by the oplog window and have no consumer groups.
"$lookup makes MongoDB relational."It works, but unindexed or correlated $lookup on large collections is slow; reshape the data.
"Atlas Serverless is the cheap tier."Serverless instances were retired in 2026; Flex clusters replaced them.
"Sharding fixes a slow query."A query without the shard key becomes a broadcast to every shard.

Cheat sheet ​

TopicWhat to remember
Document size16 MB max; bound every array; GridFS for files
ObjectId12 bytes: 4 time, 5 random, 3 counter; client-generated; monotonic
Embed vs referenceRead together = embed; unbounded or high-cardinality = reference
PatternsBucket, computed, subset, extended reference, attribute, outlier, polymorphic, schema versioning
Anti-patternsUnbounded arrays, massive number of collections, bloated documents, unnecessary indexes
Compound indexESR: Equality, Sort, Range (ERS if the range is very selective)
Explainexplain("executionStats"): IXSCAN, no SORT, keys ≈ docs ≈ returned
Aggregation$match first, narrow early, index $lookup foreign fields, $group 100 MB then spill
Write concernw: "majority" default; wtimeout does not undo
Read concernlocal default; majority for durable reads; snapshot in transactions
Read preferenceprimary for read-your-writes; maxStalenessSeconds >= 90
TransactionsUnder 60 s, retry on TransientTransactionError, commit retry on UnknownTransactionCommitResult
Replica set50 members, 7 voting; election after 10 s; median under 12 s
ShardingHigh-cardinality, low-frequency, query-present shard key; 128 MB ranges; zones for residency
WiredTigerCheckpoint 60 s, journal 100 ms, snappy/prefix compression, cache 50% of (RAM − 1 GB)

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A product document embeds every review and has started failing updates. What is happening and what are two fixes? Must-know ​

Answer

Answer: The unbounded-array anti-pattern is pushing the document towards the 16 MB limit (and making every update rewrite a large document). Apply the subset pattern (embed the newest N reviews, keep all in a reviews collection) or reference from the child (product_id on each review). See Anti-patterns.

2 — Your query filters user_id and status by equality, ranges on total_cents and sorts by created_at. In what order should the compound index fields be? Important ​

Answer

Answer: ESR: { user_id: 1, status: 1, created_at: -1, total_cents: 1 }. Putting the range before the sort forces an in-memory SORT stage, unless the range is very selective (ERS). See ESR.

3 — What three numbers in explain("executionStats") tell you whether an index is good? Important ​

Answer

Answer: nReturned, totalKeysExamined and totalDocsExamined. Ideally all three are close; totalDocsExamined: 0 means a covered query. Also check the winning plan has no SORT stage. See Reading explain.

4 — A write acknowledged with w: 1, j: true disappeared after a failover. Why? Good to know ​

Answer

Answer: It was journaled only on the old primary. The new primary never received it, and when the old primary rejoined, the write was rolled back. Only w: "majority" writes survive elections. See Write concern.

5 — Why might a user not see their profile change right after saving it, and how do you fix that in MongoDB? Important ​

Answer

Answer: The read went to a lagging secondary. Read from the primary, or use a causally consistent session with majority read and write concerns so the secondary waits for afterClusterTime. See Causal consistency.

6 — Which transaction errors may you retry, and how? Important ​

Answer

Answer: Errors labelled TransientTransactionError (such as WriteConflict, code 112): retry the whole transaction. UnknownTransactionCommitResult: retry the commit only. WithTransaction in Go and attempts in Laravel do this for you. See Transactions.

7 — Your replica set is two data nodes and an arbiter. One data node fails. What happens to w: "majority" writes? Important ​

Answer

Answer: They cannot be acknowledged, because only one data-bearing member is left and the arbiter holds no data. The primary stays up (the arbiter's vote keeps a voting majority), but majority writes time out or wait, and cache pressure grows. See Replica sets.

8 — You sharded events on { created_at: 1 }. What goes wrong and what do you do? Important ​

Answer

Answer: A monotonic shard key sends every insert to the chunk holding the highest range: one hot shard. Reshard with reshardCollection onto a hashed key or a compound key such as { device_id: 1, created_at: 1 }. See Sharding.

9 — When does a query on a sharded collection become a broadcast? Important ​

Answer

Answer: When its filter does not include the shard key (or a prefix of a compound key), mongos cannot target a shard and sends it to every shard (SHARD_MERGE in explain). See Sharding.

10 — A change-stream consumer was down for three days and now fails to resume. Why? Good to know ​

Answer

Answer: Its resume token is older than the oldest oplog entry (ChangeStreamHistoryLost). Increase the oplog size or oplogMinRetentionHours, and implement a full resync path. See Change streams.

11 — When should you choose PostgreSQL jsonb over MongoDB? Must-know ​

Answer

Answer: When the data is mostly relational with some flexible attributes, when cross-entity invariants and ad-hoc joins are common, and when one primary is enough. See Choosing.

Glossary ​

TermMeaning
BSONBinary JSON-like serialisation with extra types; MongoDB's storage and wire format
16 MB limitMaximum BSON document size (16 mebibytes)
ObjectId12-byte default _id: timestamp, per-process random value, counter
Decimal128128-bit decimal BSON type for exact money values
Embedding / referencingChild data inside the parent document vs in another document linked by id
Bucket patternGroup a series into documents of up to N items
Computed patternStore derived values (totals, counts) updated on write
Subset patternEmbed only the hot part of a large related list
Extended referenceCopy a few display fields of a referenced document next to its id
Attribute patternTurn many similar optional fields into an array of k/v pairs with one index
Outlier patternHandle the rare oversized document with overflow documents
Polymorphic patternSeveral document shapes in one collection with a type field
Schema versioningschema_version field so old and new shapes coexist during migration
Unbounded arraysAnti-pattern: arrays that grow without limit
Massive number of collectionsAnti-pattern: a collection per day/user/tenant, each with its own _id index
Bloated documentsAnti-pattern: fields not accessed together stored together, inflating the working set
Unnecessary indexesAnti-pattern: unused or prefix-redundant indexes that slow writes
Compound index / ESRMulti-field index; order Equality, Sort, Range
Multikey indexIndex on an array field, one entry per element
Text indexTokenised, stemmed index for $text; one per collection
Wildcard indexIndex over arbitrary subfield paths ($**)
TTL indexIndex with expireAfterSeconds; a background monitor deletes expired documents
Partial indexIndex only documents matching partialFilterExpression
Sparse indexIndex only documents that have the field
Hashed indexIndex on the hash of a value; used for hashed sharding
2dsphereGeospatial index for GeoJSON on a sphere
explain / winningPlan / winning planPlanner output; the plan chosen after the trial race
COLLSCAN / IXSCAN / FETCH / SORTPlan stages: full scan, index scan, document fetch, in-memory sort
executionStatsExplain verbosity that runs the plan and reports keys/docs examined
Aggregation pipelineSequence of stages ($match, $project, $lookup, $group, $facet, $merge, $out)
allowDiskUseLets blocking stages spill to temporary files past 100 MB
Write concernAcknowledgment requirement: w, j, wtimeout
Read concernWhich data version a read may return: local, available, majority, linearizable, snapshot
Read preferenceWhich member serves a read; tags and maxStalenessSeconds
Causal consistencySession guarantee: read your writes, monotonic reads/writes, writes follow reads
Retryable writesDriver retries a single write once; server deduplicates by transaction number
Multi-document transactionAll-or-nothing changes across documents within a session
Snapshot isolationTransaction reads one point-in-time snapshot; write-write conflicts abort
WriteConflictError 112: concurrent write to the same document; retry the transaction
TransientTransactionErrorError label: the whole transaction can be retried
UnknownTransactionCommitResultError label: commit outcome unknown; retry the commit
transactionLifetimeLimitSecondsServer parameter limiting transaction runtime (60 s default)
Replica setPrimary plus secondaries replicating via the oplog
Election / electionTimeoutMillisChoosing a new primary; triggered after 10 s without the primary
OplogCapped collection local.oplog.rs of idempotent operations
PriorityMember's preference to become primary; 0 = never
ArbiterVoting member without data
Hidden member / delayed memberPriority-0 member invisible to clients / applying the oplog secondaryDelaySecs late
RollbackUndoing writes on a former primary that were not majority-replicated
mongos / config serverQuery router / replica set holding cluster metadata
Shard keyField(s) that decide which shard owns a document
Hashed sharding / ranged shardingDistribute by hash of the key / by contiguous key ranges
Chunk / range migrationA contiguous shard-key range / moving it between shards
BalancerBackground process that migrates ranges to even out shards
ZonesShard-key ranges pinned to tagged shards
Targeted / broadcast querySent to the shards owning the key / to every shard
Resharding / reshardCollectionChanging a collection's shard key online by copying data
Change streams / resume tokenOrdered feed of changes from the oplog / position to resume from
WiredTigerDefault storage engine: document-level concurrency, MVCC, compression
Document-level concurrencyOptimistic concurrency per document; intent locks above
Checkpoint / journalConsistent on-disk snapshot every 60 s / write-ahead log between checkpoints
Compression (snappy, zstd, zlib)Block compressors for collections; prefix compression for indexes
WiredTiger cacheInternal cache: larger of 50% of (RAM − 1 GB) or 256 MB
$jsonSchema / validationLevelServer-side schema validation / strict or moderate enforcement
SCRAM / x.509Password-based challenge-response auth / certificate auth
RBACRole-based access control with built-in and custom roles
Encryption at restEncrypted storage engine (Enterprise, Atlas)
Field-level encryption (CSFLE) / Queryable EncryptionClient-side encryption of fields; searchable variant
mongodump / mongorestoreLogical backup and restore tools; --oplog / --oplogReplay
Snapshots / PITRFilesystem or cloud snapshots / point-in-time recovery by replaying the oplog
Profiler / slowmsCaptures slow operations into system.profile / slow threshold
mongostat / mongotop / CompassLive server stats / time per collection / GUI with visual explain
Atlas Search / Vector SearchLucene full-text search ($search) / ANN vector search ($vectorSearch)
Serverless / FlexRetired Atlas serverless instances / the tier that replaced them
jsonbPostgreSQL binary JSON type with GIN indexing
mongo-driver/v2 / WithTransactionOfficial Go driver module / its retrying transaction helper
laravel-mongodbOfficial Laravel integration package mongodb/laravel-mongodb

References ​

Built by Morteza Negahi