MongoDB — The Judgement Behind Document Databases
MongoDB — Embedding and Execution Plans
Goal
On a real MongoDB 8.0 running inside the Pod, you insert documents, find them, change them, group them, apply a schema, embed, and read execution plans as numbers. At the end, you take on an incident where report numbers disagree with the ledger and find and fix a different cause for each store.
Why it matters
A document database blocks nothing at insert time. The string '3' and the number 3, status and state, PAID and paid can
all land mixed in one collection without a single error. Those values surface months later, when an aggregation quietly returns a wrong number, and
by then you reach the cause only if you know to suspect the shape of the data rather than the query. The first eight steps are where you learn that shape (types, arrays, schemas, plans)
by hand, and the final incident is where you apply it to a real failure.
Steps
- 5 or more documents in
items— all with name, qty (a number), and tags (an array) - Save documents with qty > 0, projected to name and qty only
- Create a name index and confirm the plan changes to IXSCAN
- Change just one field
- Unwind the array and total per tag
- Actually reject a wrong type with
$jsonSchema - Embed line items in an order
- Write down the execution plans of two queries as numbers
- Incident — store reports differ from the payment ledger
Connecting
mongosh labdb
Steps 1–8 use labdb. The step 9 incident creates its own separate shop DB and is self-contained. PostgreSQL is also running in the same Pod,
so psql works as is — if you solve the same problem in both databases, the differences become clear.
Notes
- Put result files under
/root/work/mongo/(mkdir -p /root/work/mongo). To save JSON from the shell, write something likemongosh --quiet labdb --eval 'JSON.stringify(db.items.find({},{_id:0}).toArray())' > <file>. - Common mistakes: wrapping numbers in quotes so they go in as strings, and assigning a whole document without an operator when updating.
- Incident tool:
incident listshows the incidents you can start and a one-line symptom for each, andincident show <name>shows the ticket again. Starting the same incident again resets it to the initial broken state with new random material (answers you wrote earlier will no longer match). - The report is
/root/incident/<name>/report.txt. Write one<target>: <cause-code>line per target, and addevidence: <line>at the end. The evidence is one line of output you saw before fixing, copied verbatim (20 characters or more) — the grader matches it whole against the observation record captured during the incident. The grader looks at the actual state after your fix first, and uses the report to confirm your diagnosis. - The lab Pod has no volume. When the session ends, your work under
/rootdisappears.
Insert documents — a value can be an array
Connect with mongosh labdb and insert 5 or more documents into the items collection. Give every document name (a string), qty (a number), and tags (an array of strings, at least 1), and make one of them have name set to red-backpack (its qty must be something other than 10). So that differences show up in later steps, also insert at least one document whose qty is 0 and at least one whose tags contains camping.
Direction: a document DB does not create tables in advance — the collection appears the moment you insert, and you can store an array as a value as is. Tools: insertMany, countDocuments, find. Specifics: write numbers without quotes ('3' is a string, so it drops out of later size comparisons and totals). After inserting everything, check by eye with db.items.find() that all five documents have the same shape.
Every document in items (5 or more) has name, qty (a number), and tags (an array of strings), and there are red-backpack, qty: 0, and camping-tag documents
Fetch only the fields you need
Find only the documents whose qty is greater than 0, fetch just the two fields name and qty (without _id), and save the result as a JSON array to /root/work/mongo/02-query.json.
Direction: the search condition (filter) and the fields to fetch (projection) are given separately as the first and second arguments of find. Tools: the comparison operator $gt, _id: 0 in the projection, mongosh --quiet --eval and JSON.stringify(….toArray()). Specifics: when saving from the shell, redirect the output of --eval to a file as in the lab instructions example. 0 is not "greater than 0".
02-query.json holds the current data's qty > 0 documents with only name and qty (contents match)
Create an index and see whether the plan changes
Create an index on name in items, and confirm that the execution plan of the query for name equal to red-backpack changes from COLLSCAN to IXSCAN (ask once before creating the index too).
Direction: if you ask the same query twice, before and after the index, you can see what changes. Tools: createIndex, queryPlanner.winningPlan of find(…).explain(). Specifics: the plan has nested stages — go down past the outer stage (FETCH) into inputStage to find IXSCAN and indexName.
A name index exists and that query uses IXSCAN
Change just one field
Change only the qty of red-backpack to the number 10. name and tags must remain as they are.
Direction: replacing a whole document and fixing one field are different operations. Tools: updateOne with a field update operator, and findOne to check. Specifics: if you pass a whole document without an operator as the second argument, the fields you did not write disappear — after the change, be sure to check that tags is still there.
qty is 10, and name and tags remain unchanged
Unwind the array and group by tag
Unwind tags one tag at a time, compute the qty total per tag, and save it to /root/work/mongo/05-bytag.json as a JSON array of documents with _id (the tag) and total (the total).
Direction: if you group the array as is, the whole ['camping','hiking'] becomes a single key — you get per-tag groups only by making one document per element and then grouping. Tools: $unwind and $group ($sum) in aggregate([...]). Specifics: in the _id of $group and in $sum, put $ before the field name to say you mean "the value of that field". Name the result field total.
The per-tag totals in 05-bytag.json match the current data
Apply a schema to a document DB too
Apply $jsonSchema validation to the orders collection. Make item (a string) and qty (a number) required, and confirm by inserting one yourself that putting a string in qty is actually rejected. A correct document (item a string · qty a number) must be accepted.
Direction: in a document DB, a schema is a validation rule attached to the collection. The standard is not whether you wrote the rule but whether a wrong document is actually blocked. Tools: db.createCollection(<name>, {validator: {$jsonSchema: …}}) (use collMod if it already exists), bsonType and required, and insertOne with try/catch to check. Specifics: if you narrow the numeric type to int, 1.5 is rejected; narrow it to double and 1 is rejected — look for a broader type name that accepts any number. With validationAction set to warn, only a warning is logged and the document goes in.
The $jsonSchema on orders actually rejects a wrong type and a missing item or qty, and accepts a correct document
Embed what is read together
Insert one order into orders, embedding the line items as a lines array (2 or more, each item a document with name (a string) and qty (a number)). Include item and qty too so that it passes the step 6 validation, and confirm that the order can be found by lines.name.
Direction: if the order screen always reads the order and its line items together, putting the line items inside the order document brings them in one read. Tools: insertOne, and the dot notation 'lines.name' for finding a field inside an array. Specifics: the elements of lines must be {name: …, qty: …} documents, not strings. If the validation rule blocks you, read which field failed in the error's details.
One order document has 2 or more lines (each a name and qty document) · it can be found by lines.name
Read the plans and write them down as numbers
Read the execution plans of two queries with explain('executionStats') and write them to /root/work/mongo/08-explain.txt — {name: 'red-backpack'} (indexed) on an indexed: line, and {tags: 'camping'} (not indexed) on an unindexed: line. On each line write <STAGE> docsExamined=<n> nReturned=<n> (STAGE is IXSCAN or COLLSCAN). Do not create an index on tags.
Direction: the stage name is only half the story — how many documents were opened for each document returned (totalDocsExamined versus nReturned) is the index's report card. Tools: executionStats.totalDocsExamined and nReturned of explain('executionStats'), queryPlanner.winningPlan. Specifics: the grader re-runs explain on the same two queries against the current data and compares the numbers — if you changed the step 1 documents, measure again.
The stage, documents examined, and documents returned on both lines of 08-explain.txt match the current execution plans
Incident — store reports differ from the payment ledger
Running incident mg-report-drift starts the incident (it creates a new shop DB unrelated to the earlier steps). The three store reports (/root/shop/reports/store-a.js, store-b.js, store-c.js) produce numbers different from the payment ledger (/root/shop/ledger.txt). Find the cause for each store and fix it so that all three reports produce the same numbers as the ledger. If the data is the cause, restore the data to its original shape (other screens read the same collection); if the script is the cause, fix the script. Do not delete or insert documents, and do not hard-code numbers into the reports. In /root/incident/mg-report-drift/report.txt, write three lines store-a: <code>, store-b: <code>, and store-c: <code>, plus one document line that shows the cause, evidence: <line> (exactly as printed with JSON.stringify before fixing). The code for each store is one of the following: case-mismatch (status values have mixed case), duplicate-docs (the same order was inserted twice), elem-match (an array condition is not bound to a single element), field-renamed (documents with a renamed field are mixed in), string-number (strings are mixed into a numeric field).
Direction: if a number is lower than the ledger, look for "documents dropped by the condition"; if higher, look for "documents wrongly matched". For each store, count the shape of the data first (field names, types, values), and if the data is fine, compare that store's script condition with the other stores. Tools: countDocuments with $type, $exists, $nin; $group to collect the status values; for fixing, $rename in updateMany or an update pipeline ($toInt, $toLower); $elemMatch for array conditions. Specifics: for the evidence, paste one line exactly as printed before fixing with db.orders.find({…}).forEach(d => print(JSON.stringify(d))). After fixing, run the three reports again and compare them line by line with ledger.txt.
The three reports match the ledger and also hold on other data · all documents are back in their original shape · a cause code per store and an evidence line