MongoDB interview questions: document boundaries, invariants and recovery
Start from the read and write paths, then decide which facts belong in one bounded document. Put invariants in atomic predicates or database constraints where possible; name the topology and recovery contract when they span documents.
For: Backend engineers designing or operating MongoDB-backed services.
Guide scope and versions
MongoDB Server 8.x concepts. The executable single-document reservation example is specified for PyMongo 4.19.0 and a disposable MongoDB 8.x replica-free fixture. Transaction and change-stream traces are discussion-only and require replica-set or sharded topology where stated. No production workload or failover behavior is established.
Question 1 of 10
When should related records share one document?
Embed fields that are read and changed together when their growth is bounded. Reference independently queried or unbounded children, and state how cross-document consistency is maintained.
For an order, bounded line snapshots can live with the order because checkout reads and accepts them together. An unbounded event history should not become an ever-growing array. Keep catalog identity separate when products are independently updated, then snapshot the agreed price and description on the order.
Estimate worst-case document size and write contention, not just average size. Embedding removes a join from the common read path, but duplicated facts need an owner and an update policy. A reference adds another read and leaves a multi-record invariant to the application or a transaction.
MongoDB model trace · Worked example
Order { _id, tenantId, status, lines: [{ sku, quantity, unitPriceMinor, catalogRevision }] }
CatalogProduct { _id: sku, revision, priceMinor, available }
// Keep order.lines bounded by the checkout limit; put unbounded events in a separate collection.
Discussion-only data shape, not executable MongoDB code. It records a bounded checkout snapshot and leaves independently changing catalog state in its own collection.
Non-executable model trace; no workload or document-size measurement.
Follow-up: What changes if order lines grow without a fixed limit?
Move unbounded history to a separately paged collection or impose a product-enforced maximum. Document the extra read and consistency boundary.
Make the eligibility condition and decrement one atomic update on the same inventory document. Check the matched result and make retries idempotent at the business-operation boundary.
A read-then-write sequence can let two requests both observe quantity 1. The update filter must include available >= requested; $inc then applies only if that predicate still matches. A unique reservation key prevents a client retry from creating a second logical reservation, but the inventory mutation and reservation record span two documents unless the reservation ledger is embedded or a transaction is used.
The executable fixture stores at most two operation IDs in one disposable document and rejects all other keys. That makes the proof bounded; it is not a production ledger design. Production must choose a retention/archive boundary or a separately indexed idempotency collection. A repeated key with a different quantity is rejected rather than silently replaying a different request.
Python / PyMongo 4.19.0 · Worked example
from pymongo import MongoClient
import re
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
client = MongoClient('mongodb://mongo:27017/?directConnection=true', serverSelectionTimeoutMS=5000)
db = client['proof']
inventory = db['inventory']
inventory.delete_many({})
inventory.insert_one({'_id': 'T-7:SKU-9', 'tenant_id': 'T-7', 'sku': 'SKU-9', 'available': 3, 'reservations': {}})
ALLOWED_KEYS = {'R-1', 'R-2'}
race_barrier = None
def reserve(bucket_id, tenant_id, sku, operation_id, quantity, collection=inventory):
if operation_id not in ALLOWED_KEYS or not re.fullmatch(r'[A-Z0-9-]{1,20}', operation_id):
raise ValueError('operation id is outside this bounded fixture')
if isinstance(quantity, bool) or not isinstance(quantity, int) or quantity <= 0:
raise ValueError('quantity must be a positive integer')
prior = collection.find_one({'_id': bucket_id, 'tenant_id': tenant_id, 'sku': sku})
if prior and operation_id in prior['reservations']:
if prior['reservations'][operation_id] != quantity:
raise ValueError('idempotency key reused with a different payload')
return quantity
if race_barrier is not None:
race_barrier.wait(timeout=5)
result = collection.update_one(
{'_id': bucket_id, 'tenant_id': tenant_id, 'sku': sku, 'available': {'$gte': quantity}, f'reservations.{operation_id}': {'$exists': False}},
{'$inc': {'available': -quantity}, '$set': {f'reservations.{operation_id}': quantity}},
)
if result.modified_count == 1:
return quantity
current = collection.find_one({'_id': bucket_id, 'tenant_id': tenant_id, 'sku': sku})
if current and operation_id in current['reservations']:
if current['reservations'][operation_id] != quantity:
raise ValueError('idempotency key reused with a different payload')
return quantity
raise ValueError('reservation rejected: missing bucket, wrong tenant, or insufficient stock')
race_barrier = Barrier(2)
race_clients = [MongoClient('mongodb://mongo:27017/?directConnection=true', serverSelectionTimeoutMS=5000) for _ in range(2)]
race_collections = [race_client['proof']['inventory'] for race_client in race_clients]
with ThreadPoolExecutor(max_workers=2) as pool:
attempts = [pool.submit(reserve, 'T-7:SKU-9', 'T-7', 'SKU-9', 'R-1', 2, collection)
for collection in race_collections]
assert [attempt.result(timeout=10) for attempt in attempts] == [2, 2]
for race_client in race_clients:
race_client.close()
race_barrier = None
assert reserve('T-7:SKU-9', 'T-7', 'SKU-9', 'R-1', 2) == 2
assert inventory.find_one({'_id': 'T-7:SKU-9'})['available'] == 1
for tenant, key, amount in [('T-8', 'R-2', 1), ('T-7', 'R-2', 2)]:
try:
reserve('T-7:SKU-9', tenant, 'SKU-9', key, amount)
except ValueError:
pass
else:
raise AssertionError('invalid tenant or insufficient stock unexpectedly succeeded')
try:
reserve('T-7:SKU-9', 'T-7', 'SKU-9', 'R-1', 1)
except ValueError:
pass
else:
raise AssertionError('same idempotency key with changed payload unexpectedly succeeded')
assert inventory.find_one({'_id': 'T-7:SKU-9'})['available'] == 1
assert inventory.find_one({'_id': 'T-7:SKU-9'})['reservations'] == {'R-1': 2}
for invalid in (0, -1, 1.5, True):
try:
reserve('T-7:SKU-9', 'T-7', 'SKU-9', 'R-2', invalid)
except ValueError:
pass
else:
raise AssertionError('non-positive or non-integer quantity unexpectedly succeeded')
try:
reserve('T-7:SKU-9', 'T-7', 'SKU-9', 'R-3', 1)
except ValueError:
pass
else:
raise AssertionError('operation key outside the fixture cap unexpectedly succeeded')
assert inventory.find_one({'_id': 'T-7:SKU-9'})['available'] == 1
client.close()
The isolated runner executes these exact bytes against a disposable MongoDB server. Assertions cover success, same-payload retry, tenant rejection, insufficient-stock rejection, changed-payload key reuse, and unchanged final state. The fixture has a hard two-key allowlist, so the embedded map cannot grow; this is deliberately not a production idempotency-ledger recipe.
Self-contained synthetic MongoDB 8.0.34 / PyMongo 4.19.0 example; single-node replication and failover are outside this example.
Follow-up: Does the conditional update make an email or payment exactly once?
No. It protects this document mutation. External effects need an outbox or another durable handoff plus idempotent consumers; retries can still repeat an effect after an ambiguous response.
If the invariant spans collections, use a transaction on a replica set or sharded cluster, check the conditional update matched one document, then write the order in that same transaction. If that topology or coordination cost is unsuitable, use an explicit reservation/saga with reconciliation.
This example executes both a successful cross-collection commit and an insufficient-stock failure on a disposable single-node replica set. A standalone server cannot prove transaction behavior. A one-node replica set demonstrates transaction semantics only; it says nothing about failover, replication durability, or production availability.
Retry the whole transaction only for transient transaction errors as the driver contract permits. A commit result can be ambiguous after network loss; resolve by stable operation identity before issuing a new business operation. Do not rerun a callback that performed an email or payment side effect.
The isolated runner starts a disposable single-node replica set and executes this exact body. Assertions prove the success path and that a failed conditional update aborts without changing stock or creating an order. This does not test multi-node durability, failover, or external side effects.
Self-contained synthetic MongoDB 8.0.34 / PyMongo 4.19.0 example; single-node replication and failover are outside this example.
Follow-up: What is the role of an outbox here?
Write the business record and an outbox record in the same transaction, then publish asynchronously with an idempotent consumer. The outbox closes the database-to-publisher gap but delivery can still repeat.
Start from the exact filter, sort and projection, then inspect explain('executionStats') on representative data. Check examined keys/documents, returned rows, sort stages and index size under writes.
A tenant-scoped feed might filter by tenant and status, sort by creation time and _id, and paginate. A compound index should reflect that access path and its equality/sort fields. A different query shape may need another index; adding every candidate index increases write and storage costs.
A tiny fixture proves syntax and plan shape only weakly. It cannot establish production selectivity, cache residency, skew or latency. Use representative sanitized distributions and compare execution statistics without treating a single winning plan as a permanent guarantee.
Plan review trace · Worked example
A tenant-scoped order feed returns 50 accepted orders, newest first. Review the server's plan record for index use, rows examined, sort work and returned count against a representative tenant distribution. Then compare index write cost and footprint. No plan record or timing is supplied here.
Human-readable review trace, not a command or executable query. The article runtime does not create a representative orders corpus or assert an index plan.
Non-executable plan review trace; production selectivity not measured.
Follow-up: Which explain values would make you investigate?
A large documentsExamined-to-nReturned ratio, unexpected COLLSCAN or blocking SORT, and a plan that changes with realistic tenant skew deserve investigation. Measure write cost and index footprint too.
When can a secondary read miss an acknowledged write?
A secondary can lag. In MongoDB 8.0, a majority write acknowledgement can arrive before secondaries apply the corresponding oplog entry, so an immediate independent secondary read may be stale.
Choose read preference and read concern from the user promise. A dashboard may tolerate bounded staleness; a post-checkout confirmation usually needs read-your-own-write behavior. Causally consistent sessions with majority read and write concerns provide causal guarantees when used according to the driver contract.
A majority acknowledgement does not mean every secondary has applied the document change at that instant. Do not repair a stale read by blindly issuing another write; first identify whether the read path or state transition is wrong.
Consistency failure trace · Worked example
Client A receives acknowledgement for an order write. Before a secondary has applied that change, client B reads the secondary and temporarily sees no order. The application must route the confirmation according to its read-your-write promise. This is a possible schedule, not an observed incident.
Human-readable failure trace; it contains no client operation or executable command and does not simulate replication delay.
Non-executable consistency trace; no replica-set lag experiment performed.
Follow-up: Does a majority write acknowledgement alone guarantee a later secondary read sees the write?
No. MongoDB 8.0 acknowledges after majority durable oplog persistence while application on secondaries can continue asynchronously. Use a causally consistent session for the required causal read, or choose a primary read where suitable.
Use a stable unique keyset order for deep feeds. A high-water mark can bound membership only when the chosen ordering and records follow explicit append-only/immutable assumptions; it does not create a point-in-time snapshot. Use a database snapshot or materialized export version when updates/deletes must not change the export while pages are read.
A cursor on (createdAt, _id) avoids large offset scans and disambiguates equal timestamps. The next filter must follow the same descending order and include rows strictly after the last tuple. Validate and sign opaque client cursors if tampering could cross tenant or filter boundaries.
A high-water key can exclude later inserts above the captured boundary, but updates and deletions within that range can still change later pages. State append-only and immutable-field assumptions when they hold. For a stable export, use a snapshot-capable read or materialize an export version and accept its retention/storage cost.
Pagination decision trace · Worked example
The first page ends at timestamp 2026-10-25T10:00:00Z and order ID O-50. The next page continues strictly after that timestamp-and-ID pair in descending order, under the same tenant and status filter. The cursor must be validated and the result is not a frozen export.
Human-readable trace, not a database query. It includes no cursor parser or executable pagination command.
Non-executable pagination trace; no dataset or plan assertion.
Follow-up: Does keyset pagination produce a point-in-time export?
No. It bounds traversal work and gives stable ordering, but concurrent inserts/updates/deletes can change page membership. Use a snapshot or high-water mark when the export contract requires one.
How do you evolve documents while old writers still run?
Use an expand, migrate, contract sequence. Make readers tolerate both forms first, deploy writers that converge on the new form, backfill in bounded batches, measure leftovers, then remove compatibility only after old writers are gone.
A validator can reject invalid new writes, but tightening validation before every writer is compatible can cause production failures. A background migration needs checkpoints, idempotent updates, bounded batches and a resume strategy. Validate both old and new shapes during the transition.
For a renamed field, dual-read temporarily, write the canonical field, backfill by stable ranges, and remove the old field only after counts and application versions show the cutover is complete. Keep the rollback path explicit; a destructive drop can make code rollback impossible.
Migration decision trace · Worked example
A writer changes a product's price field while older application instances are still active. The safe sequence is compatible readers, new writers, checkpointed historical backfill, proof that old writers and legacy shapes are gone, then stricter validation. A batch size and rollback plan still depend on the production workload.
Human-readable failure trace with no migration command or executable database operation.
Non-executable migration trace; no data mutation performed.
Follow-up: When should validation become strict?
After compatible writers are deployed, historical documents are backfilled, and the residual legacy count is zero under the real access path. Then enforce the invariant before removing the dual-read fallback.
A change stream is a resumable view of database changes subject to oplog retention and resume-token validity. It is not an unlimited event archive or exactly-once external delivery system.
Persist resume tokens only after downstream effects have reached the chosen durable boundary. A crash after publishing but before saving the token can repeat a message; saving the token first can lose one. Use idempotent consumers and reconcile from durable business state when a token expires or the oplog no longer covers the gap.
Change streams require replica-set or sharded-cluster topology. Test invalidation, resume behavior, consumer restart, retention gaps and duplicate effects in the actual topology before claiming recovery.
Change-stream recovery trace · Worked example
A worker publishes an event, then crashes before recording its resume position. Restart can publish that event again. If the saved position has fallen outside retained history, continuity cannot be claimed; reconcile from durable business records before starting a new stream position.
Human-readable recovery trace; no stream cursor, publisher or database operation is executable here.
Non-executable topology/recovery trace; replica-set and oplog-retention behavior untested.
Follow-up: What if MongoDB can no longer resume from the token?
Stop claiming continuity, rebuild or reconcile from durable application state, then establish a new stream position. Define the gap handling before the token expires.
How do you keep tenant boundaries out of client control?
Derive tenant identity from authenticated server-side context and include it in every tenant-scoped query and update predicate. Enforce least privilege and validate document shape at the database boundary.
A client-supplied tenant ID is a selector, not proof of membership. Bind the authenticated tenant into the repository call, compound unique indexes and update filters. Test cross-tenant reads and writes explicitly, including nested references and administrative paths.
Use TLS, scoped database users and secret rotation. Reject operator-shaped untrusted filters rather than passing arbitrary JSON into a query. Redact credentials and sensitive document fields from logs; a correct query predicate does not make broad database credentials safe.
Tenant authorization failure trace · Worked example
An authenticated principal belongs to tenant T-7 but submits tenant T-8 in the request body. The service must ignore that field as authority, bind T-7 from authentication and scope every database operation to T-7. A cross-tenant attempt must not reveal the record or mutate it.
Human-readable security trace, not application or query code. It does not test an authentication provider or database role.
Non-executable security trace; authorization integration not tested.
Follow-up: Would a compound tenant index replace authorization checks?
No. The index improves a query path. Authorization still needs a server-owned tenant predicate and access-control tests.
What should happen when the write response is lost?
Treat a network timeout as an unknown outcome, not proof that the server rejected the write. Resolve the stable operation key against durable state before issuing a new business operation.
A server can apply a reservation and then lose the response before the client receives it. Retrying with the same key should return the original result and leave stock unchanged. A new key would represent a second request and could reserve stock again if the caller guessed incorrectly.
Driver retryable writes cover specific eligible operations and failure classes; they do not make arbitrary multi-step workflows or external notifications exactly once. State retry limits, key retention and the resolution path for an ambiguous commit.
Ambiguous outcome trace · Worked example
The server applies reservation R-1 and decrements available stock from 3 to 1. The acknowledgement is lost. The client retries R-1, reads the stored result and returns the same reservation without another decrement. If that result cannot be found, the client reports an unresolved outcome for reconciliation rather than inventing a new operation key.
Human-readable failure sequence; no retry loop or network fault is executed by this example.
Non-executable retry/recovery trace; network ambiguity is not simulated.
Follow-up: Can the client retry forever until it gets a response?
No. Bound attempts and time, preserve the stable operation key, and expose an unresolved state for reconciliation. Infinite retries can duplicate non-idempotent side effects or hide a persistent outage.
These are Hacker News job posts that mention these technologies, not employee earnings or a measure of what a skill adds to pay. The amounts summarize annualized advertised minimums in approximate USD. Groups can overlap and differ in roles, locations and dates.
Approximate USD using ECB daily reference rates as of 2026-10-30. Original currencies and offer ranges remain on the source listings. These figures cover posts tagged MongoDB, rather than every job in the broader technology family.