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 for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why a document database, and the trade-off against relational | Why MongoDB exists |
BSON types, the 16 MB limit, ObjectId | The document model |
| Embedding vs referencing and the eight named patterns | Schema design |
| Unbounded arrays, too many collections, bloated documents, too many indexes | Anti-patterns |
Index types, ESR, explain(), the winning plan | Indexes and explain |
$match, $project, $lookup, $group, $facet, $merge, $out | Aggregation pipeline |
w, j, readConcern, read preference, causal sessions, retryable writes | Consistency dials |
| Multi-document transactions, limits, WriteConflict, error labels | Transactions |
| Elections, oplog, priority, arbiters, hidden and delayed members | Replica sets |
| Shard key, hashed vs ranged, zones, balancer, resharding | Sharding |
| Change streams and resume tokens | Change streams |
| WiredTiger, knobs, error codes | Mechanics |
$jsonSchema, security, backups, profiler and tools, Atlas | Operations |
| Go driver v2 and Laravel MongoDB code | Go, Laravel |
| Hot documents, counters, pagination, idempotent upserts | Solving the classic problems |
MongoDB or PostgreSQL jsonb | Choosing |
| Monolith to sharded multi-region | In architecture |
| A replica set in Docker, write concern, ESR explain, sharding | Lab |
| Wrong beliefs, a cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The model.
| Concept | In plain words | Tiny example | The number to remember |
|---|---|---|---|
| Document | A JSON-like record stored as BSON | { _id, user_id, items: [...] } | 16 MB maximum per document |
| Collection | A set of documents, no fixed columns | orders | Every collection carries an _id index |
ObjectId | Default _id, made by the client | ObjectId("665f...") | 12 bytes: 4 time, 5 random, 3 counter |
| Single-document atomicity | One document write is all-or-nothing | $inc stock and $push a log line together | No transaction needed inside one document |
| Replica set | One primary, secondaries replay its oplog | 3 data-bearing members | Up to 50 members, 7 voting |
| Sharded cluster | Data split by shard key across replica sets | mongos + config servers + shards | Default range size 128 MB |
The dials.
| Dial | Options | Safe default | What it costs |
|---|---|---|---|
| Write concern | w: 0, w: 1, w: "majority", j: true, wtimeout | w: "majority" (the server default) | Latency of a replica round trip |
| Read concern | local, available, majority, linearizable, snapshot | local for plain reads; majority when you act on what you read | Possibly older data, or a primary round trip for linearizable |
| Read preference | primary, primaryPreferred, secondary, secondaryPreferred, nearest | primary | Secondaries can be behind (maxStalenessSeconds >= 90) |
| Causal consistency | Session option | On for sessions in current drivers | Only meaningful with majority read and write concerns |
| Retryable writes | retryWrites=true | On by default | One automatic retry; needs an idempotent-by-design write |
| Transactions | startTransaction / WithTransaction | Only when one document cannot hold the invariant | 60 s default lifetime, more cache pressure, WriteConflict aborts |
The three things to do.
| Situation | Do this |
|---|---|
| Designing a collection | Write down the top queries first; embed what is read together, reference what grows without bound; pick a pattern by name |
| Adding an index | Order compound keys Equality, Sort, Range (ESR), then confirm IXSCAN, no SORT stage and totalKeysExamined close to nReturned in explain("executionStats") |
| Writing data that matters | w: "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 time | Model access patterns; embed what is read together |
Schema enforced by CREATE TABLE and constraints | Flexible by default; enforce with $jsonSchema validators and unique indexes |
| Multi-row transactions are the normal unit | One 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 engine | Native 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
$jsonSchemavalidation and aschema_versionfield, 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 type | Alias for $type / bsonType | Use it for | Trap |
|---|---|---|---|
| Double | double | Measurements | Default numeric type from JavaScript |
| 32-bit / 64-bit integer | int / long | Counters, IDs, cents | Mixing int and long is fine for queries, not for strict validators |
| Decimal128 | decimal | Money, exact decimals | Driver support needed in every client |
| String | string | UTF-8 text | Collation decides case-insensitive comparison |
| Date | date | Timestamps (ms since epoch, UTC) | Store UTC; strings sort but do not range-compare as dates |
| Timestamp | timestamp | Internal (oplog, cluster time) | Not for application dates |
| ObjectId | objectId | Default _id | Not a secret, not strictly monotonic across clients |
| Binary data | binData | UUIDs (subtype 4), hashes, encrypted fields | UUID subtype differences between old drivers |
| Array / Object | array / object | Embedded lists and subdocuments | Arrays create multikey index entries |
| Null / missing | null | Absent values | { f: null } matches both null and missing |
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 choice | Advantage | Cost |
|---|---|---|
ObjectId (default) | No round trip, time-ordered, 12 bytes | Monotonic: hot spot as a ranged shard key |
UUID v4 (binData subtype 4) | Random, globally unique, generated anywhere | 16 bytes; random inserts spread across the B-tree, more cache churn |
| UUIDv7 / ULID | Time-ordered and globally unique | Same hot-spot issue as ObjectId for ranged sharding |
| Natural key | Upsert by business key, no secondary unique index | Must truly never change |
Compound _id | Encodes tenant + id; one unique index | Field 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".
| Relationship | Example | Recommended shape |
|---|---|---|
| One-to-one | User and settings | Embed |
| One-to-few | Order and its 1–50 lines; user and 3 addresses | Embed the array |
| One-to-many (bounded hundreds) | Product and its latest reviews | Subset pattern: embed the newest N, reference the rest |
| One-to-squillions | Device and its readings; account and its log lines | Reference from the child (device_id on each reading), or bucket |
| Many-to-many | Students and courses | Arrays of ids on one or both sides, plus extended references for display fields |
| Shared, changing entity | Product price in every order | Reference, or copy deliberately as a snapshot (the order should keep the price at purchase time) |
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 orderReal 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
| Pattern | Problem it solves | Shape | Cost |
|---|---|---|---|
| Bucket | Too many tiny documents (time series, events) | One document holds up to N items of a series | Bucket management code; partial buckets |
| Computed | The same expensive aggregation on every read | Store the running total/count; update on write | Writes do more; value can drift if a writer forgets |
| Subset | Hot document too big because of a long list | Embed the newest/most-used N, keep the full list in another collection | Two writes per new item |
| Extended reference | Constant $lookup just to show a name | Copy the few display fields of the referenced document next to the reference | Copies go stale; refresh on change or accept a snapshot |
| Attribute | Many sparse, similar fields that all need indexes | attrs: [{k: "color", v: "red"}, ...] with one index on { "attrs.k": 1, "attrs.v": 1 } | Queries become $elemMatch; validation is harder |
| Outlier | A few documents are far bigger than the rest | Flag the outlier (has_overflow: true) and move the excess to overflow documents | Code path for the outlier |
| Polymorphic | Different shapes of the same thing in one collection | One collection, a type field, shared fields indexed | Validation per type with oneOf |
| Schema versioning | Changing shape without a stop-the-world migration | schema_version field; code reads both versions; migrate lazily | Two 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.
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 IXSCANReal 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.
// 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 collectionReal 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:
// 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).
| Pattern | Index you need | Validation approach |
|---|---|---|
| Extended reference | Index on the reference _id for fan-out refresh | Required display fields |
| Attribute | { "attrs.k": 1, "attrs.v": 1 } | attrs items require k and v |
| Outlier | Same as normal documents; overflow keyed by parent id | has_overflow is boolean |
| Polymorphic | Shared fields plus partial indexes per type | $jsonSchema with oneOf per type |
| Schema versioning | Usually none extra; optionally partial index on old version for the backfill | schema_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-pattern | Symptom you see | Fix |
|---|---|---|
| Unbounded arrays | Slow $push, rising document size, error 17419 near 16 MB | Subset, bucket, or reference from the child |
| Massive number of collections | Thousands of _id indexes, slow startup, high file-handle count | One collection with a discriminator field (day, tenant_id) and a compound index |
| Bloated documents | Working set does not fit in cache; high bytes read per query | Split rarely read fields (description, history) into another collection |
| Unnecessary indexes | Write latency up, $indexStats shows accesses.ops: 0 | Drop 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 scan | Index with a case-insensitive collation and query with the same collation |
| Separating data that is accessed together | $lookup on every request | Embed or extended reference |
// 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."
| Type | Create | Serves | Limits and traps |
|---|---|---|---|
| Single field | createIndex({ email: 1 }) | Equality, range, sort on that field | Direction irrelevant for single-field sorts |
| Compound | createIndex({ user_id: 1, status: 1, created_at: -1 }) | Queries on any prefix; sort in index order or its reverse | Order follows ESR; mixed directions must match the sort |
| Multikey | Automatic when an indexed field holds an array | Matching any element | One entry per element; at most one array field per compound index key |
| Text | createIndex({ title: "text", body: "text" }) | $text: { $search: "..." } with stemming | "A collection can have only one text index"; for relevance search use Atlas Search |
| Wildcard | createIndex({ "attrs.$**": 1 }) | Queries on unknown or arbitrary subfields | Cannot serve compound sorts like a planned compound index |
| TTL | createIndex({ last_seen: 1 }, { expireAfterSeconds: 3600 }) | Automatic deletion | Background monitor; documents may linger up to about 60 s after expiry; single date field |
| Partial | createIndex({ created_at: 1 }, { partialFilterExpression: { status: "open" } }) | Queries whose filter implies the expression | Query must include the filter condition to use it |
| Sparse | createIndex({ coupon: 1 }, { sparse: true, unique: true }) | Unique on optional fields | Sorts using it can silently skip documents |
| Hashed | createIndex({ tenant_id: "hashed" }) | Equality; hashed sharding | No range queries; no arrays; no unique |
| 2dsphere | createIndex({ location: "2dsphere" }) | $near, $geoWithin, $geoIntersects on GeoJSON | Coordinates are [longitude, latitude] |
| Unique | createIndex({ email: 1 }, { unique: true }) | Constraint | E11000 duplicate key error on violation |
| Clustered / hidden | createCollection(..., { clusteredIndex }) / hideIndex() | Storage ordered by key / test a drop | Hidden 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.
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 stage | Meaning | Healthy value |
|---|---|---|
queryPlanner.winningPlan | The chosen tree of stages | FETCH over IXSCAN, or PROJECTION_COVERED over IXSCAN |
rejectedPlans | Plans that lost the race | Many rejected plans suggest overlapping indexes |
COLLSCAN | Full collection scan | Only on tiny collections or deliberate full scans |
IXSCAN with indexBounds | Index range scanned | Tight bounds on the equality prefix |
SORT / SORT_KEY_GENERATOR | In-memory sort | Absent for paginated queries |
FETCH with filter | Documents loaded then filtered | Filter should be small; move fields into the index |
executionStats.nReturned | Documents returned | Close to totalKeysExamined |
totalKeysExamined / totalDocsExamined | Work done | Ratio to nReturned near 1; totalDocsExamined: 0 means covered |
executionTimeMillis | Time of the winning plan | Stable across runs |
SHARD_MERGE / SINGLE_SHARD | Sharded: broadcast vs targeted | SINGLE_SHARD for OLTP queries |
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."
| Stage | What it does | Optimisation note |
|---|---|---|
$match | Filters documents | First, so it can use an index; on sharded clusters include the shard key |
$project / $set / $unset | Reshape, add or remove fields | Early narrowing cuts memory; the optimiser moves independent $match before them |
$sort + $limit | Order and cut | Coalesce into a top-k sort; a leading $sort can use an index |
$lookup | Left outer join to another collection | Index foreignField; $lookup + $unwind coalesce; prefer embedding for hot paths |
$unwind | One document per array element | Multiplies document count; filter first |
$group | Group by key with accumulators ($sum, $avg, $push, $addToSet) | Blocking; 100 MB per stage, then spill (allowDiskUse); $push can exceed it with no spill |
$facet | Several sub-pipelines on the same input | The single output document must stay under 16 MB; as the first stage it does a COLLSCAN, so put $match before it |
$bucket / $bucketAuto | Histograms | Good inside $facet |
$merge | Upsert results into a collection (incremental materialised view) | Can write to a sharded collection; whenMatched / whenNotMatched |
$out | Replace a collection with the results | Atomic replace that keeps the old collection's index definitions; cannot output to a sharded collection (use $merge) |
$unionWith | Append another collection's results | Like UNION ALL |
$setWindowFields | Window functions (running totals, ranks) | Partition by an indexed key |
$search / $vectorSearch | Atlas Search / Vector Search | Must be the first stage |
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.
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 concern | Acknowledged when | Survives failover? | Typical use |
|---|---|---|---|
w: 0 | Never (fire and forget) | No, and you never learn of errors | Metrics you can lose |
w: 1 | Primary applied it in memory | No | Logs, caches, high-volume telemetry |
w: 1, j: true | Primary journaled it | Survives primary restart, not failover | Single-node durability |
w: "majority" | Majority of data-bearing voting members applied it (journaled by default) | Yes | Default; orders, payments, anything you act on |
w: <tag> | Members matching a tag set (e.g. two data centres) | Yes, across zones | Multi-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 concern | Can return data later rolled back? | Sees your own w: 1 write? | Cost |
|---|---|---|---|
local | Yes | Yes on the primary | Cheapest |
available | Yes (and orphans on shards) | Usually | Cheapest on sharded clusters |
majority | No | Only after it is majority-committed | Possibly slightly old data |
linearizable | No | Yes, and every completed majority write | Round trip to confirm primary; use maxTimeMS |
snapshot | No (with majority commit) | Inside its transaction | Holds 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.
| Mode | Reads from | Use for | Risk |
|---|---|---|---|
primary | Primary only | Read-your-writes, anything you act on | Unavailable during an election |
primaryPreferred | Primary, else a secondary | Availability during failover | Stale reads during failover |
secondary | Secondaries only | Isolated analytics | Lag; errors if no secondary |
secondaryPreferred | Secondary, else primary | Dashboards, exports | Lag |
nearest | Lowest latency member | Geo-distributed read-mostly data | Lag; 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.
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 profileFix: 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 behaviour | Value / rule |
|---|---|
| Deployment | Replica 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 transaction | maxTransactionLockRequestTimeoutMillis, then abort (also hit when DDL is pending on the same collection) |
| Size | Many oplog entries per transaction; each entry still under 16 MB |
| Cache pressure | Big transactions abort with WriteConflict or TransactionTooLargeForCache |
| Write concern | Set on the transaction, never per operation inside it (error) |
| Not allowed | Writes to capped collections and system.* collections; creating collections and indexes is allowed, with restrictions (read concern local) |
| Sharded with arbiters | Transactions that write to a shard with an arbiter error and abort |
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 / label | Meaning | What to do |
|---|---|---|
WriteConflict (112) | Another writer changed the document first | Retry the whole transaction (the label says so) |
Label TransientTransactionError | Whole transaction can be retried safely | Re-run the callback from the start |
Label UnknownTransactionCommitResult | Commit 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 |
TransactionTooLargeForCache | Transaction cannot fit in the WiredTiger cache | Split the work; it will never succeed as is |
E11000 duplicate key (11000) | Unique index violated | Business 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.
| Member type | Votes | Can become primary | Serves reads | Use |
|---|---|---|---|---|
| Primary | 1 | Is primary | Yes | All writes |
| Secondary (priority > 0) | 1 | Yes | With read preference | Failover target |
| Priority 0 | 0 or 1 | No | Yes | A DR site that should never lead |
| Hidden | 0 or 1 | No (must be priority 0) | No ("invisible to client applications") | Analytics, backups |
| Delayed | 0 or 1 | No (priority 0, should be hidden) | No | secondaryDelaySecs window to undo human error |
| Arbiter | 1 ("exactly 1 election vote") | No (no data) | No | Tie-breaker when a third data node is impossible |
| Non-voting | 0 | No | Yes | Read 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".
| Strategy | How keys map to shards | Good at | Bad at |
|---|---|---|---|
| Ranged sharding | Contiguous key ranges | Range queries on the key, zone placement | Monotonic keys: one hot shard |
| Hashed sharding | Ranges of the hash of the key | Even write spread for monotonic keys | Range queries become broadcasts |
Compound key ({ tenant_id: 1, _id: 1 }) | Ranges over the pair | Targeted per-tenant queries, spread within a tenant | Very large single tenants need a hashed suffix |
| Zones | Key ranges pinned to tagged shards | Data residency (EU data on EU shards), hot/cold tiers | Balancer only moves within the zone |
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| Operation | Command | Note |
|---|---|---|
| Shard a collection | sh.shardCollection("shop.orders", { tenant_id: 1, order_id: 1 }) | Needs a supporting index |
| Hashed | sh.shardCollection("shop.events", { device_id: "hashed" }) | Pre-split for empty collections |
| Zones | sh.addShardToZone("shardA", "EU"), sh.updateZoneKeyRange(...) | Key ranges per zone |
| Balancer | sh.getBalancerState(), sh.stopBalancer(), balancing windows | Stop during backups |
| Range size | chunksize in config.settings (default 128 MB) | Larger = fewer migrations |
| Refine key | refineCollectionShardKey | Adds suffix fields, no data copy |
| Reshard | reshardCollection (5.0+), same key with forceRedistribution (8.0+) | Needs disk for a full copy; one such operation at a time |
| Unshard / move | unshardCollection, moveCollection | Mutually 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.
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 resyncReal 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.
| Capability | MongoDB | PostgreSQL | MySQL InnoDB | Others |
|---|---|---|---|---|
| Document storage | Native BSON, 16 MB per document | jsonb 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 documents | Any path, multikey, wildcard | GIN on jsonb (jsonb_path_ops), expression indexes | Multi-valued and functional indexes | CockroachDB inverted indexes on JSONB |
| Atomic unit | Single document; transactions optional | Any transaction | Any transaction | Cassandra: partition; DynamoDB: item (+ transactions) |
| Default write durability | w: "majority" | Local commit, synchronous_commit on; replicas async by default | Local commit; replicas async by default | CockroachDB: Raft majority on every write |
| Built-in failover | Replica set elections | No (Patroni, cloud managed) | Group Replication / InnoDB Cluster | CockroachDB, Spanner: consensus built in |
| Built-in sharding | Yes (mongos, balancer) | No (Citus, partitioning) | No (Vitess) | CockroachDB, Spanner, Cassandra: yes |
| Isolation for multi-record work | Snapshot isolation in transactions | Read Committed default, SSI available | Repeatable Read default | CockroachDB Serializable default |
| Change feed | Change streams | Logical decoding | Binlog | CockroachDB 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".
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 lostHow 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
| Knob | Where | Default | When to change |
|---|---|---|---|
storage.wiredTiger.engineConfig.cacheSizeGB / --wiredTigerCacheSizePct | mongod.conf | 50% of (RAM − 1 GB), min 256 MB | Containers; co-located processes |
storage.wiredTiger.collectionConfig.blockCompressor | mongod.conf | snappy | zstd for better ratio on cold data |
storage.journal.commitIntervalMs | mongod.conf | 100 | Rarely |
replication.oplogSizeMB / oplogMinRetentionHours | mongod.conf / replSetResizeOplog | 5% of disk (990 MB – 50 GB) | Long maintenance windows, slow consumers |
settings.electionTimeoutMillis | replica set config | 10000 | Flaky networks (raise) |
members[n].priority, hidden, secondaryDelaySecs, votes | replica set config | 1, false, 0, 1 | DR members, analytics nodes |
setDefaultRWConcern | admin command | w: "majority", read local | Cluster-wide policy |
transactionLifetimeLimitSeconds | setParameter | 60 | Never raise as a fix; shorten transactions |
maxTransactionLockRequestTimeoutMillis | setParameter | small (milliseconds) | Brief DDL contention |
slowms, profiler level | db.setProfilingLevel() | 100 ms, level 0 | Diagnose slow queries |
chunksize | config.settings | 128 MB | Huge collections |
allowDiskUse / allowDiskUseByDefault | per aggregate / setParameter | true by default | Strict memory policies |
Error codes you will catch Must-know
| Code / name | Meaning | Retry? |
|---|---|---|
11000 DuplicateKey (E11000) | Unique index violated | No; treat as conflict or idempotent success |
112 WriteConflict | Concurrent write to the same document in a transaction | Yes, whole transaction (label TransientTransactionError) |
251 NoSuchTransaction | Transaction aborted/expired | Yes, from the start |
50 MaxTimeMSExpired | Operation hit maxTimeMS | Maybe, after fixing the query |
10107 NotWritablePrimary, 189 PrimarySteppedDown, 91 ShutdownInProgress | Failover in progress | Yes (retryable writes do it once automatically) |
64 WriteConcernFailed (wtimeout) | Not replicated in time; write may still apply | Check before retrying; make writes idempotent |
121 DocumentValidationFailure | $jsonSchema rejected the write | No; fix the data |
10334 BSONObjectTooLarge, 17419 | Document over 16 MB | No; fix the schema |
292 QueryExceededMemoryLimitNoDiskUseAllowed | Blocking stage over 100 MB without disk use | No; add an index, $match earlier, or allow disk use |
286 ChangeStreamHistoryLost | Resume token fell out of the oplog | No; resnapshot the consumer |
13 Unauthorized, 18 AuthenticationFailed | RBAC / credentials | No |
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.
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
| Layer | MongoDB feature | Note |
|---|---|---|
| Authentication | SCRAM-SHA-256 (default), x.509 client certificates, LDAP/Kerberos/OIDC (Enterprise/Atlas) | Enable with security.authorization: enabled; x.509 also for member auth (clusterAuthMode) |
| Authorization | RBAC: built-in roles (read, readWrite, dbAdmin, clusterMonitor, backup) and custom roles | One user per service, least privilege |
| In transit | TLS (net.tls.mode: requireTLS) | Also between replica set members |
| Encryption at rest | WiredTiger encrypted storage engine with KMIP or a local key file | "Available in MongoDB Enterprise only"; always on in Atlas |
| Field-level encryption | Client-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 Encryption | Randomised encryption with equality, range, prefix/suffix/substring queries | Newer alternative to CSFLE |
| Auditing | Audit log (Enterprise/Atlas) | DDL, auth, CRUD filters |
| Injection | Operator 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
| Method | How | RPO / restore | Caveats |
|---|---|---|---|
mongodump / mongorestore | Logical BSON export; --oplog captures writes during the dump, --oplogReplay applies them | Point of dump end; slow restore (indexes rebuilt) | Small data sets; for sharded clusters pause the balancer and DDL; not a sharded PITR tool |
| Filesystem snapshots | LVM/EBS snapshot with journal on the same volume, or fsyncLock | Snapshot time; fast restore | Must be consistent across shards (stop balancer) |
| Hidden member for backups | Dump or snapshot from a hidden secondary | No load on serving members | Watch oplog window |
| PITR via oplog | Base snapshot + continuous oplog capture, replay to a timestamp (--oplogLimit) | Seconds | Requires oplog retention covering the gap |
| Atlas Cloud Backup / Ops Manager | Managed snapshots + continuous PITR | Minutes to seconds | Paid; sharded-consistent |
General backup design (RPO/RTO, testing restores): Backup, PITR & Disaster Recovery.
Performance tooling: profiler, mongostat, mongotop, Compass Good to know
| Tool | What it shows | Use it to |
|---|---|---|
Database profiler (db.setProfilingLevel(1, { slowms: 50 })) | Slow operations in system.profile with plan summary, keys/docs examined | Find queries without indexes ("The profiler collects data for operations that exceed the slowms threshold") |
| Slow query log | Same, in the mongod log | Always-on, low cost |
explain("executionStats") | Plan and work of one query | Prove an index works |
$indexStats, db.collection.stats(), $collStats | Index usage, sizes, avgObjSize | Remove unused indexes, size the cache |
mongostat | Per-second inserts, queries, updates, dirty/used cache % | Live capacity view |
mongotop | Read/write time per collection | Find the hot collection |
db.currentOp() / killOp | Running operations | Kill a runaway aggregation |
rs.status(), rs.printSecondaryReplicationInfo() | Member states, replication lag | Lag alerts |
sh.status(), sh.balancerCollectionStatus() | Chunks per shard, balancer | Sharding health |
| Compass | GUI: schema analysis, visual explain, index suggestions, aggregation builder | Exploration and teaching |
| Atlas Performance Advisor / Query Profiler | Suggested indexes, slow query scatter | Managed 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.
// 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 }.
// 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).
// 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.
// 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
// 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
// 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
// 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
// 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
// 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
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Lost update on a counter or stock | Atomic update operators | updateOne({ _id, qty: { $gte: n } }, { $inc: { qty: -n } }) | No transaction, no race | Only for single-document invariants |
| Read-modify-write of a whole document | Optimistic concurrency | version field in the filter, $inc: {version: 1}; 0 matched = conflict | Works across requests | Client retry loop |
| Exactly one document per business key | Unique index + upsert | updateOne({email}, {$setOnInsert: ...}, {upsert: true}) | Idempotent | Concurrent upserts may raise E11000: retry once |
| Paging a large feed | Keyset pagination | find({ created_at: { $lt: last } }).sort({ created_at: -1 }).limit(20) on an index | Constant cost per page | No "jump to page 500"; see Pagination |
| Hot document under heavy writes | Split counter | N sub-documents or N documents {_id: "c:7:shard3"}, sum on read | Spreads write locks | Reads aggregate N values |
| Two documents must change together | Transaction or redesign | WithTransaction; or embed both into one document | Atomic | Cost, 60 s limit, WriteConflict retries |
| Duplicate processing of events | Idempotency key | Unique index on event_id in a processed collection | Safe redelivery | Storage for keys (TTL index to expire) |
Lost update
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// mongosh: atomic, conditional decrement
db.stock.updateOne({ sku: "A-1", qty: { $gte: 1 } }, { $inc: { qty: -1 } })
// { matchedCount: 0 } for the loser -> "sold out"// 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}}}})// 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
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// 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
| Situation | What the driver does | What you do |
|---|---|---|
| Primary steps down during a single write | Retryable writes resend once | Nothing, if retryWrites is on (default) |
| Network error during a read | Retryable reads retry once | Nothing |
Transaction TransientTransactionError | WithTransaction / Laravel attempts re-run the callback | Keep the callback idempotent |
UnknownTransactionCommitResult | WithTransaction retries the commit | Nothing |
wtimeout / WriteConcernFailed | Returns error; write may still apply | Re-read before retrying; idempotent writes |
| E11000 on concurrent upsert | Returns error | Retry 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.
-- 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 constraint | Choose | Extra technique | Reason |
|---|---|---|---|
| Aggregate-shaped reads (order + lines, profile + settings), evolving shape | MongoDB | Embedding, schema versioning, $jsonSchema | One document read, one atomic write |
| Mostly relational data with a few flexible attributes | PostgreSQL jsonb | GIN index on the jsonb column, generated columns for hot keys | Joins, constraints and SQL stay available |
| Cross-entity invariants on every request (ledgers, double-entry) | PostgreSQL | Serializable or FOR UPDATE | Transactions are the normal path, not the exception |
| Write scale beyond one primary, multi-region | MongoDB sharding (or distributed SQL) | Shard key + zones | Native balancer and routing |
| Ad-hoc analytics and BI joins | PostgreSQL or a warehouse | Change streams/CDC into the warehouse | $lookup is not a planner-driven join engine |
| Time series and event buckets | MongoDB time series / bucket pattern, or TimescaleDB | TTL indexes | Both fine; pick what the team runs |
| Full-text plus vector plus operational data in one place | MongoDB Atlas (Search, Vector Search) or PostgreSQL (FTS + pgvector) | — | See Full-Text Search and Vector Search |
| Team knows SQL, data under a few TB, one region | PostgreSQL | jsonb where needed | Fewer 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.
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 resurrectedDetails: 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×
| Load | What changes | MongoDB consequence |
|---|---|---|
| 1× (one replica set, working set fits in cache) | Indexes by ESR, embedding, defaults | explain 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 instances | Drop 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 views | Every 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.
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.
# 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 m3Experiment 2: election and failover.
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 againExperiment 3: ESR index and explain.
// 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.
# 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 }; checkdb.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
| Belief | Reality |
|---|---|
| "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
| Topic | What to remember |
|---|---|
| Document size | 16 MB max; bound every array; GridFS for files |
ObjectId | 12 bytes: 4 time, 5 random, 3 counter; client-generated; monotonic |
| Embed vs reference | Read together = embed; unbounded or high-cardinality = reference |
| Patterns | Bucket, computed, subset, extended reference, attribute, outlier, polymorphic, schema versioning |
| Anti-patterns | Unbounded arrays, massive number of collections, bloated documents, unnecessary indexes |
| Compound index | ESR: Equality, Sort, Range (ERS if the range is very selective) |
| Explain | explain("executionStats"): IXSCAN, no SORT, keys ≈ docs ≈ returned |
| Aggregation | $match first, narrow early, index $lookup foreign fields, $group 100 MB then spill |
| Write concern | w: "majority" default; wtimeout does not undo |
| Read concern | local default; majority for durable reads; snapshot in transactions |
| Read preference | primary for read-your-writes; maxStalenessSeconds >= 90 |
| Transactions | Under 60 s, retry on TransientTransactionError, commit retry on UnknownTransactionCommitResult |
| Replica set | 50 members, 7 voting; election after 10 s; median under 12 s |
| Sharding | High-cardinality, low-frequency, query-present shard key; 128 MB ranges; zones for residency |
| WiredTiger | Checkpoint 60 s, journal 100 ms, snappy/prefix compression, cache 50% of (RAM − 1 GB) |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| BSON | Binary JSON-like serialisation with extra types; MongoDB's storage and wire format |
| 16 MB limit | Maximum BSON document size (16 mebibytes) |
| ObjectId | 12-byte default _id: timestamp, per-process random value, counter |
| Decimal128 | 128-bit decimal BSON type for exact money values |
| Embedding / referencing | Child data inside the parent document vs in another document linked by id |
| Bucket pattern | Group a series into documents of up to N items |
| Computed pattern | Store derived values (totals, counts) updated on write |
| Subset pattern | Embed only the hot part of a large related list |
| Extended reference | Copy a few display fields of a referenced document next to its id |
| Attribute pattern | Turn many similar optional fields into an array of k/v pairs with one index |
| Outlier pattern | Handle the rare oversized document with overflow documents |
| Polymorphic pattern | Several document shapes in one collection with a type field |
| Schema versioning | schema_version field so old and new shapes coexist during migration |
| Unbounded arrays | Anti-pattern: arrays that grow without limit |
| Massive number of collections | Anti-pattern: a collection per day/user/tenant, each with its own _id index |
| Bloated documents | Anti-pattern: fields not accessed together stored together, inflating the working set |
| Unnecessary indexes | Anti-pattern: unused or prefix-redundant indexes that slow writes |
| Compound index / ESR | Multi-field index; order Equality, Sort, Range |
| Multikey index | Index on an array field, one entry per element |
| Text index | Tokenised, stemmed index for $text; one per collection |
| Wildcard index | Index over arbitrary subfield paths ($**) |
| TTL index | Index with expireAfterSeconds; a background monitor deletes expired documents |
| Partial index | Index only documents matching partialFilterExpression |
| Sparse index | Index only documents that have the field |
| Hashed index | Index on the hash of a value; used for hashed sharding |
| 2dsphere | Geospatial index for GeoJSON on a sphere |
| explain / winningPlan / winning plan | Planner output; the plan chosen after the trial race |
| COLLSCAN / IXSCAN / FETCH / SORT | Plan stages: full scan, index scan, document fetch, in-memory sort |
| executionStats | Explain verbosity that runs the plan and reports keys/docs examined |
| Aggregation pipeline | Sequence of stages ($match, $project, $lookup, $group, $facet, $merge, $out) |
| allowDiskUse | Lets blocking stages spill to temporary files past 100 MB |
| Write concern | Acknowledgment requirement: w, j, wtimeout |
| Read concern | Which data version a read may return: local, available, majority, linearizable, snapshot |
| Read preference | Which member serves a read; tags and maxStalenessSeconds |
| Causal consistency | Session guarantee: read your writes, monotonic reads/writes, writes follow reads |
| Retryable writes | Driver retries a single write once; server deduplicates by transaction number |
| Multi-document transaction | All-or-nothing changes across documents within a session |
| Snapshot isolation | Transaction reads one point-in-time snapshot; write-write conflicts abort |
| WriteConflict | Error 112: concurrent write to the same document; retry the transaction |
| TransientTransactionError | Error label: the whole transaction can be retried |
| UnknownTransactionCommitResult | Error label: commit outcome unknown; retry the commit |
| transactionLifetimeLimitSeconds | Server parameter limiting transaction runtime (60 s default) |
| Replica set | Primary plus secondaries replicating via the oplog |
| Election / electionTimeoutMillis | Choosing a new primary; triggered after 10 s without the primary |
| Oplog | Capped collection local.oplog.rs of idempotent operations |
| Priority | Member's preference to become primary; 0 = never |
| Arbiter | Voting member without data |
| Hidden member / delayed member | Priority-0 member invisible to clients / applying the oplog secondaryDelaySecs late |
| Rollback | Undoing writes on a former primary that were not majority-replicated |
| mongos / config server | Query router / replica set holding cluster metadata |
| Shard key | Field(s) that decide which shard owns a document |
| Hashed sharding / ranged sharding | Distribute by hash of the key / by contiguous key ranges |
| Chunk / range migration | A contiguous shard-key range / moving it between shards |
| Balancer | Background process that migrates ranges to even out shards |
| Zones | Shard-key ranges pinned to tagged shards |
| Targeted / broadcast query | Sent to the shards owning the key / to every shard |
| Resharding / reshardCollection | Changing a collection's shard key online by copying data |
| Change streams / resume token | Ordered feed of changes from the oplog / position to resume from |
| WiredTiger | Default storage engine: document-level concurrency, MVCC, compression |
| Document-level concurrency | Optimistic concurrency per document; intent locks above |
| Checkpoint / journal | Consistent on-disk snapshot every 60 s / write-ahead log between checkpoints |
| Compression (snappy, zstd, zlib) | Block compressors for collections; prefix compression for indexes |
| WiredTiger cache | Internal cache: larger of 50% of (RAM − 1 GB) or 256 MB |
| $jsonSchema / validationLevel | Server-side schema validation / strict or moderate enforcement |
| SCRAM / x.509 | Password-based challenge-response auth / certificate auth |
| RBAC | Role-based access control with built-in and custom roles |
| Encryption at rest | Encrypted storage engine (Enterprise, Atlas) |
| Field-level encryption (CSFLE) / Queryable Encryption | Client-side encryption of fields; searchable variant |
| mongodump / mongorestore | Logical backup and restore tools; --oplog / --oplogReplay |
| Snapshots / PITR | Filesystem or cloud snapshots / point-in-time recovery by replaying the oplog |
| Profiler / slowms | Captures slow operations into system.profile / slow threshold |
| mongostat / mongotop / Compass | Live server stats / time per collection / GUI with visual explain |
| Atlas Search / Vector Search | Lucene full-text search ($search) / ANN vector search ($vectorSearch) |
| Serverless / Flex | Retired Atlas serverless instances / the tier that replaced them |
| jsonb | PostgreSQL binary JSON type with GIN indexing |
| mongo-driver/v2 / WithTransaction | Official Go driver module / its retrying transaction helper |
| laravel-mongodb | Official Laravel integration package mongodb/laravel-mongodb |
References
- MongoDB Manual: Documents, BSON Types, ObjectId(), Limits and Thresholds
- Data modeling: Embedded Data Versus References, Schema Design Patterns, Bucket Pattern, Subset Pattern, Outlier Pattern, Attribute Pattern, Computed Values, Polymorphic Data, Schema Versioning, Handle Duplicate Data
- Anti-patterns: Schema Design Anti-Patterns, Avoid Unbounded Arrays, Reduce the Number of Collections, Bloated Documents, Remove Unnecessary Indexes
- Indexes: The ESR Guideline, Multikey, Text, Wildcard, Hashed, 2dsphere, TTL, Partial, Sparse, Explain Results
- Aggregation: Pipeline Optimization,
$lookup,$group,$facet,$merge,$out - Consistency: Write Concern, Read Concern, Read Preference, maxStalenessSeconds, Causal Consistency and Read and Write Concerns, Retryable Writes
- Transactions: Transactions, Production Considerations, Transactions and Operations, Read Concern "snapshot"
- Replication: Replica Set Elections, Replica Set Architectures, Oplog, Hidden Members, Delayed Members, Arbiter, Deploy a Replica Set
- Sharding: Sharding, Choose a Shard Key, Hashed Sharding, Ranged Sharding, Zones, Balancer, Query Routing, Reshard a Collection, sh.shardCollection(), Deploy a Sharded Cluster
- Change Streams, WiredTiger Storage Engine, Journaling, Schema Validation
- Security: Authentication, SCRAM, x.509, Role-Based Access Control, Encryption at Rest, CSFLE, Queryable Encryption
- Operations: Backup Methods, mongodump, mongostat, mongotop, Database Profiler, Profiler Output, Monitoring, Compass
- Atlas: MongoDB Search, Vector Search Overview, Migrate to Flex Clusters
- PostgreSQL: JSON Types
- Go driver v2: documentation, pkg.go.dev
mongo,options,writeconcern,readpref - Laravel MongoDB: documentation, Transactions, Schema Builder, Query Builder, Aggregation Builder