Course outline

MongoDB / Basic: document foundations / Lesson 7

Distinguish null and missing fields

Predict MongoDB query results for a present value, explicit null, and an absent field.

About 22 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Explain the difference between a missing field and BSON null.
  • Use an existence predicate to identify absent fields.
  • Test filters against representative documents and application rules.
  • Distinguish absent scalar fields from explicit null using suitable predicates.
  • Design and verify updates that preserve the difference between clearing and removal.

Define the meaning of absence

A profile may have a known city, an explicit null, or no city field at all. These states can have different business meanings: unknown, deliberately cleared, or not yet collected. Decide which states the application accepts and how each is displayed or updated. A query must implement that contract rather than assume that every document has the same shape.

Create three synthetic profiles

The following mongosh example is for a new disposable MongoDB 8.0-compatible collection. It inserts one string value, one explicit BSON null, and one document without the city field. It does not connect to a configured application deployment. Use a fresh collection so the identifiers do not collide with earlier test data.

javascript Create a small profile fixture
db.lab_profiles.insertMany([
  { _id: 1, name: "Amina", city: "Cairo" },
  { _id: 2, name: "Noor", city: null },
  { _id: 3, name: "Leo" }
]);

Profile 1 has city Cairo, profile 2 has city null, and profile 3 has no city field. These statements describe the declared synthetic documents, not an observed production dataset.

Compare null and existence filters

A query for a field equal to null matches explicit null and missing fields under the documented MongoDB behavior. An existence predicate can select the absent field separately. Run the two queries against the disposable fixture and compare their identifiers. The projections and sort keep the example focused and deterministic; actual driver results depend on the target collection.

javascript Compare two filters
db.lab_profiles.find({ city: null }, { _id: 1 }).sort({ _id: 1 });
db.lab_profiles.find({ city: { $exists: false } }, { _id: 1 }).sort({ _id: 1 });

For this fixture the first filter matches ids 2 and 3; the second matches only id 3. Profile 1 has a non-null city. The example does not claim that these commands were executed on a live service.

Validate the value shape

A field can exist with a value of an unexpected BSON type, so existence alone does not establish a valid city. Test empty strings, arrays, and other shapes according to the applicationโ€™s schema rules. When the distinction between null and missing matters, use a documented type or existence condition appropriate to the query and data model. Preserve the distinction at the driver and API boundary.

Test reads and updates together

Use synthetic documents to test a missing field, an explicit null, and a valid value through the deployed driver. Check how a partial update handles an omitted property versus one explicitly set to null. Verify both the returned document and the intended user-visible behavior. If the schema evolves, test old and new writers during the migration rather than silently treating all three states as equivalent.

Define four distinct states

An absent field is not the same document shape as a field explicitly set to BSON null. A valid value, an empty string and numeric zero add further states that must not be collapsed by application truthiness. Decide what each state means in the business domain: for example, missing may mean not collected while null may mean deliberately cleared, but that interpretation is an application contract rather than a universal MongoDB rule. Record how a user interface displays each state and how reports classify it. The examples in this lesson use synthetic scalar fields unless an array is explicitly stated; they are illustrative and were not executed against a server.

Build the state table before selecting an operator. For each field write its permitted BSON types, whether absence is allowed, and the meaning of an explicit null. For example, a delivery instruction may be absent before collection and null after a customer clears it; that distinction only exists if writers preserve it. An empty string can be present yet invalid under a separate validation rule. A query can identify a storage state, but cannot infer why a user produced that state. Record that reason separately if it affects workflow or auditing.

Choose the predicate for the question

For a scalar city field, equality to null matches both explicit null and a missing field. $exists:false selects documents where the field is absent, while $exists:true includes a present field even if its value is null. A type-aware test can select explicit BSON null for a scalar schema, but query $type has array matching behavior that needs separate review if arrays are allowed. Test one valid string, one null, one missing field and at least one wrong type. Write expected document identifiers before running a query in a disposable environment. An existence match establishes presence, not validity of the stored value.

The equality predicate is deliberately broad. To count only absent scalar fields use $exists:false; to count explicit null use query $type:10, with a scalar-schema assumption. Conversely $ne:null selects present non-null fields but can include wrong types and empty strings. These sets answer different questions. When arrays are permitted, query $type can match array elements, so do not assume that a null match proves the entire field itself is null. Use an appropriate aggregation expression and test representative arrays before drawing that conclusion.

Separate omission, clearing and removal

A partial API request may omit a property to mean leave the existing value unchanged, while explicit null may mean clear it. That meaning must be deliberately implemented; the JSON input alone does not guarantee how a driver constructs an update. $set to null keeps the field present, whereas $unset removes it. Confirm the resulting stored shape and the response semantics in tests. A replacement document has different omitted-field behavior from a partial operator update, so do not infer the effect of an omitted API property without inspecting the write mapping. Authorization and validation still apply to both clearing and removal.

The write path should translate each request state deliberately. If an omitted property means no change, do not place it into the update document. If null means clear but retain evidence of the field, map it to $set; if removal is the intended contract, map a distinct operation to $unset. The two results behave differently under $exists. A full replacement must include every field meant to survive, unlike an operator update. Before designing a migration, inventory older clients that might send a full object or silently insert defaults.

Keep unknowns visible in reports

A report that excludes missing and null values may produce a plausible subtotal while silently omitting records. Count the input population and classify known, null, missing and invalid values separately before applying a business rule for totals. Zero is a numeric value and should not be counted as absence merely because it is false-like in an application language. Preserve rejected records for investigation, and document whether a missing value is allowed for an older schema version. A default used for display must not silently become an authoritative stored value or hide an incomplete migration.

For a report, define mutually exclusive categories at the document level and reconcile their counts against the total population. A display fallback such as $ifNull can group missing and null into one label, which is useful for presentation but destroys their distinction in that output. Keep a separate classification if later analysis requires the original state. Decide whether invalid values are excluded, corrected or reviewed, and document the decision with the report. Presence and non-nullness are not a substitute for checking the required type and business range.

Test a migration across readers and writers

Build an isolated fixture with a valid scalar, null, missing, empty string and wrong type. Verify both query results and actual driver serialization, because an omitted property and a null property can be handled differently by client libraries. Test old and new writers during a schema transition and reconcile counts before and after conversion. If an update turns missing into null, check whether that is a deliberate migration or an accidental loss of meaning. For array-valued fields and nested paths, prepare separate fixtures and consult the operator documentation rather than assuming scalar examples cover every shape. No real server or learner data is used in these reasoned examples.

Verify proposed predicates on small fixtures before applying any change to an authorized isolated test collection. Include explicit null, absent, valid, empty and wrong-type values, and compare identifiers rather than only totals. Exercise both the read filter and the write mapping through the intended driver, since language serialization affects what is sent. Reconcile before-and-after counts, and inspect sampled stored shapes for accidental collapsing of states. The snippets here describe synthetic inputs and reasoned outcomes; they have not been executed on a MongoDB server.

20 worked examples

1. Presence is not validity

Problem: Which documents have a rating field, including an explicit null?

  1. The first two documents contain the key; the third does not.
  2. Null does not make an existing field disappear.
text Synthetic fixture and reasoned predicate or update
[{_id:1,rating:4},{_id:2,rating:null},{_id:3}]
filter: {rating: {$exists:true}}

This illustrative trace was not executed on a server.

Expected result: Reasoned result: 1, 2

Why this result follows: Null does not make an existing field disappear.

2. Select explicit scalar null

Problem: Which scalar status is explicitly BSON null?

  1. BSON type 10 identifies the null value in the second document.
  2. The absent key in document 3 has no scalar null value to match.
text Synthetic fixture and reasoned predicate or update
[{_id:1,status:"ready"},{_id:2,status:null},{_id:3}]
filter: {status: {$type:10}}

This illustrative trace was not executed on a server.

Expected result: Reasoned result: 2

Why this result follows: The absent key in document 3 has no scalar null value to match.

3. Non-null is not domain validation

Problem: Which present values are non-null, and which are valid positive quantities?

  1. The non-null predicate excludes both null and absence in this scalar fixture.
  2. Zero remains a present non-null number, although the positive-quantity rule rejects it.
text Synthetic fixture and reasoned predicate or update
[{_id:1,qty:0},{_id:2,qty:3},{_id:3,qty:null},{_id:4}]
filter: {qty: {$ne:null}}

This illustrative trace was not executed on a server.

Expected result: Reasoned result: 1, 2

Why this result follows: Zero remains a present non-null number, although the positive-quantity rule rejects it.

4. Clear while retaining the key

Problem: What shape results when the note is set to null?

  1. The update assigns BSON null to the existing note field.
  2. A subsequent existence test sees the key even though its previous text is gone.
text Synthetic fixture and reasoned predicate or update
before: {_id:1,note:"fragile"}
update: {$set:{note:null}}

This illustrative trace was not executed on a server.

Expected result: Reasoned result: {_id:1,note:null}

Why this result follows: A subsequent existence test sees the key even though its previous text is gone.

5. Remove a field instead

Problem: What shape follows removal of an optional note field?

  1. The unset operator removes note from the document rather than storing an empty string.
  2. An existence test for note would now be false.
text Synthetic fixture and reasoned predicate or update
before: {_id:1,note:"fragile"}
update: {$unset:{note:""}}

This illustrative trace was not executed on a server.

Expected result: Reasoned result: {_id:1}

Why this result follows: An existence test for note would now be false.

6. Display fallback loses distinctions

Problem: What display value is chosen for a null or missing label?

  1. The fallback expression treats null and missing as requiring the replacement.
  2. The displayed label alone cannot reveal which of the first two shapes was stored.
text Synthetic fixture and reasoned predicate or update
[{_id:1,label:null},{_id:2},{_id:3,label:"North"}]
expression: {$ifNull:["$label","Unknown"]}

This illustrative trace was not executed on a server.

Expected result: Reasoned result: 1: Unknown; 2: Unknown; 3: North

Why this result follows: The displayed label alone cannot reveal which of the first two shapes was stored.

7. Empty text is present

Problem: Which document has a present but empty destination?

  1. The empty string is a string value, not BSON null.
  2. The missing and null destinations therefore do not satisfy this exact string condition.
text Synthetic input for analysis
[{_id:1,dest:""},{_id:2,dest:null},{_id:3}]
filter: {dest:""}

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: 1

Why this result follows: The missing and null destinations therefore do not satisfy this exact string condition.

8. Constrain a null search

Problem: Which open shipment has a null or missing gate?

  1. Both open documents satisfy the broad null condition for gate.
  2. The closed document is excluded by the separate state condition despite its missing gate.
text Synthetic input for analysis
[{_id:1,state:"open",gate:null},{_id:2,state:"closed"},{_id:3,state:"open"}]
filter: {state:"open",gate:null}

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: 1, 3

Why this result follows: The closed document is excluded by the separate state condition despite its missing gate.

9. Nested field existence

Problem: Which profile lacks the nested contact.phone path?

  1. The first document has the nested phone key even though it is null.
  2. The path is absent both in the empty contact object and when contact itself is absent.
text Synthetic input for analysis
[{_id:1,contact:{phone:null}},{_id:2,contact:{}},{_id:3}]
filter: {"contact.phone":{$exists:false}}

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: 2, 3

Why this result follows: The path is absent both in the empty contact object and when contact itself is absent.

10. Null within an array

Problem: Can query type null match an array containing null?

  1. The query type operator can match an array element of the requested type.
  2. Therefore this predicate does not prove that the top-level tags value itself is BSON null.
text Synthetic input for analysis
[{_id:1,tags:["cold",null]},{_id:2,tags:["cold"]}]
filter: {tags:{$type:10}}

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: 1

Why this result follows: Therefore this predicate does not prove that the top-level tags value itself is BSON null.

11. Expression type distinguishes the array

Problem: What types does the aggregation expression report for these fields?

  1. Aggregation $type reports the type of the field value itself, including missing.
  2. The array containing null is consequently distinct from a field whose value is null.
text Synthetic input for analysis
[{_id:1,tags:[null]},{_id:2,tags:null},{_id:3}]
expression: {$type:"$tags"}

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: 1: array; 2: null; 3: missing

Why this result follows: The array containing null is consequently distinct from a field whose value is null.

12. Set a missing field

Problem: What happens when a missing scalar field is set to null?

  1. Setting zone creates the previously absent field with a null value.
  2. A subsequent existence predicate now includes this document.
text Synthetic input for analysis
before: {_id:7,parcel:"P"}
update: {$set:{zone:null}}

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: {_id:7,parcel:"P",zone:null}

Why this result follows: A subsequent existence predicate now includes this document.

13. Unsetting an absent field

Problem: What happens when the requested field is already absent?

  1. There is no zone field to remove from this document.
  2. The documented unset operation has no effect on that absent field.
text Synthetic input for analysis
before: {_id:8,parcel:"Q"}
update: {$unset:{zone:""}}

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: {_id:8,parcel:"Q"}

Why this result follows: The documented unset operation has no effect on that absent field.

14. Present but wrong type

Problem: Which document needs review under a scalar string contact rule?

  1. All three documents contain contact, so an existence filter returns each one.
  2. The numeric and null values fail the stated scalar-string contract even though both keys exist.
text Synthetic input for analysis
[{_id:1,contact:"desk"},{_id:2,contact:17},{_id:3,contact:null}]
filter: {contact:{$exists:true}}

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: 1, 2, 3; review 2 and 3

Why this result follows: The numeric and null values fail the stated scalar-string contract even though both keys exist.

15. Reconcile report categories

Problem: Do the classified counts cover the entire shipment population?

  1. Both five and zero are numbers in the declared fixture.
  2. Adding the mutually exclusive category counts gives four, matching the input population.
text Synthetic input for analysis
[{_id:1,weight:5},{_id:2,weight:null},{_id:3},{_id:4,weight:0}]
classification: numeric / null / missing

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: numeric: 2; null: 1; missing: 1; total: 4

Why this result follows: Adding the mutually exclusive category counts gives four, matching the input population.

16. Omitted patch property

Problem: What is retained when the patch omits the city property?

  1. The stated mapping places only name in the operator update.
  2. Because city is not targeted, its prior value remains under this explicit mapping.
text Synthetic input for analysis
stored: {_id:1,city:"Cairo",name:"A"}
request: {name:"B"}
mapped update: {$set:{name:"B"}}

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: {_id:1,city:"Cairo",name:"B"}

Why this result follows: Because city is not targeted, its prior value remains under this explicit mapping.

17. Replacement drops omitted properties

Problem: What shape follows this full replacement of a synthetic profile?

  1. The replacement supplies the complete new document apart from the immutable identity rule.
  2. Since city is absent from that replacement, it does not survive as an omitted patch property would.
text Synthetic input for analysis
before: {_id:1,city:"Cairo",name:"A"}
replacement: {_id:1,name:"B"}

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: {_id:1,name:"B"}

Why this result follows: Since city is absent from that replacement, it does not survive as an omitted patch property would.

18. Two predicates partition null matches

Problem: How can a scalar null-equality result be separated into two groups?

  1. The type predicate selects the explicit null in document 1 under the scalar assumption.
  2. The existence predicate selects the absent port in document 2; together these account for the null-equality matches.
text Synthetic input for analysis
[{_id:1,port:null},{_id:2},{_id:3,port:"A"}]
filters: {port:{$type:10}} ; {port:{$exists:false}}

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: first: 1; second: 2

Why this result follows: The existence predicate selects the absent port in document 2; together these account for the null-equality matches.

19. Fallback does not change storage

Problem: Does a projected fallback store a new value in the source?

  1. The expression produces a value in the projection for this read.
  2. No update operation was specified, so the source document remains unchanged.
text Synthetic input for analysis
source: {_id:1,city:null}
projection expression: {$ifNull:["$city","Unknown"]}

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: display: Unknown; source city: null

Why this result follows: No update operation was specified, so the source document remains unchanged.

20. Audit a failed migration count

Problem: What must be investigated when a migration changes state counts unexpectedly?

  1. The observed missing count fell by three and the null count rose by three.
  2. Only one conversion was planned, leaving two unexplained transitions to investigate in the write mapping.
text Synthetic input for analysis
before: {missing:4, null:2, known:6}
after:  {missing:1, null:5, known:6}
planned conversion: missing:1 -> null

Reasoned result; this example was not executed on a server.

Expected result: Reasoned result: unexpected conversions: 2

Why this result follows: Only one conversion was planned, leaving two unexplained transitions to investigate in the write mapping.

Common errors and fixes

A null filter returns more profiles than expected.

Why it happens
The filter also matches documents where the field is missing.
How to fix it
Use a documented condition that expresses the required distinction.
Prevent it next time
Test explicit null and absent fields separately.

An existing field is assumed to contain a valid city.

Why it happens
Existence was mistaken for type and domain validation.
How to fix it
Validate the BSON type and allowed value at the appropriate boundary.
Prevent it next time
Include wrong-type inputs in schema and application tests.

An update clears a value unexpectedly.

Why it happens
An omitted API property and explicit null were treated as the same instruction.
How to fix it
Define and implement separate update semantics.
Prevent it next time
Test partial updates through the real driver.

20 practice exercises

1. Which profile identifiers match city equal to null in the fixture?

Show hint

Identify the document with null and the one without the key.

Show worked solution

Ids 2 and 3: profile 2 has explicit null, while profile 3 lacks city. The known string value in profile 1 does not match.

The city:null condition matches document 2 with explicit null and document 3 without the field, but not the known string in document 1.

Check your solution

  • The result includes 2 and 3.
  • The result excludes 1.

2. Which identifier matches city with $exists false?

Show hint

Check for the key itself rather than the city value.

Show worked solution

Only id 3 lacks the city field. Profile 2 still has the field even though its value is null.

The $exists:false condition selects document 3 alone because city remains present in document 2 despite its null value.

Check your solution

  • The result includes 3.
  • The result excludes 2.

3. A scalar priority field is null in 1, missing in 2, zero in 3, and 4 in 4. Select present non-null records, then identify which satisfy a positive-priority rule.

Show hint

First exclude both null and missing; then apply the domain rule to the survivors.

Show worked solution

Use {priority:{$ne:null}} to select 3 and 4. Zero remains non-null, but only 4 has a positive priority; presence and the business rule are separate checks.

Check your solution

  • The first selection returns 3 and 4.
  • Only 4 satisfies the positive rule.

4. For scalar phone values null, missing, empty string, and "123" in IDs 1โ€“4, find missing fields and separately identify the only nonempty string.

Show hint

Missing is about shape; an empty string is still present.

Show worked solution

Use {phone:{$exists:false}} to identify 2. Under the stated values and nonempty-string rule, 4 alone is valid; 1 is null and 3 is empty, despite both being present.

Check your solution

  • The missing-field filter returns 2.
  • Only 4 satisfies the nonempty-string rule.

5. Documents have code values null in 1, missing in 2, [null] in 3 and "A" in 4. Compare query $type:10 with aggregation $type of the whole field.

Show hint

Query $type can match an array element; aggregation $type reports the field itself.

Show worked solution

The query {code:{$type:10}} matches 1 and 3, because the array contains null. Aggregation {$type:"$code"} reports null, missing, array and string for IDs 1โ€“4, respectively; use that distinction when the whole field must be null.

Check your solution

  • Query type 10 matches IDs 1 and 3.
  • Aggregation types are null, missing, array and string in ID order.

6. A report accepts numeric fees from 0 through 10. IDs 1โ€“4 contain 0, null, "free" and 12; all satisfy {fee:{$exists:true}}. Diagnose the filter and classify invalid IDs.

Show hint

Existence checks the key; the contract also imposes type and range.

Show worked solution

All four keys exist, so the presence filter returns all four. Only 1 satisfies the numeric range; 2 and 3 fail type, and 4 exceeds the maximum. Validate those rules separately.

Check your solution

  • The existence filter returns 1, 2, 3 and 4.
  • Only 1 satisfies the stated fee contract.

7. Starting with {_id:4,slot:"AM"}, clear slot while preserving it, then predict whether existence and null-equality filters match.

Show hint

Assignment retains the key; evaluate each read after the write.

Show worked solution

Apply {$set:{slot:null}} to produce {_id:4,slot:null}. Both {slot:{$exists:true}} and {slot:null} then match because the field is present and explicitly null. The original string is no longer stored.

Check your solution

  • The update retains slot with null.
  • Both specified filters match the result.

8. Starting with {_id:5,slot:"PM"}, compare the stored shapes and existence results after separate $set-to-null and $unset updates.

Show hint

Consider each update against the original document independently.

Show worked solution

The update {$set:{slot:null}} produces {_id:5,slot:null}, which matches {slot:{$exists:true}}. The update {$unset:{slot:""}} produces {_id:5}, which instead matches {slot:{$exists:false}}. Each operation starts from the original shape.

Check your solution

  • The first result retains a null slot.
  • The second result has no slot key.

9. An API defines omitted phone as unchanged and phone:null as clearing. Starting with phone:"123", map each request separately and compare the resulting shapes.

Show hint

Map omission to no operation on phone and explicit null to assignment.

Show worked solution

For an omitted phone, do not include phone in the update, preserving "123". For phone:null, use {$set:{phone:null}} and retain the field with null. Confirm that the actual driver sends these mappings.

Check your solution

  • Omission retains the string "123".
  • Explicit null leaves phone present with null.

10. Compare {$set:{a:4}} with replacement {_id:1,a:4} for {_id:1,a:2,b:3}; which resulting document matches {b:{$exists:false}}?

Show hint

Only the replacement defines the whole new document.

Show worked solution

The operator update leaves b:3, so it does not match the missing-b filter. The replacement lacks b and does match; both produce a:4, making the omitted field the decisive difference.

Check your solution

  • The operator result retains b:3.
  • Only the replacement matches the missing-b filter.

11. For [{_id:1,meta:{x:null}},{_id:2,meta:{}},{_id:3}], partition the scalar meta.x:null matches into explicit null and missing paths.

Show hint

Use a dotted path in both type and existence filters.

Show worked solution

The filter {"meta.x":{$type:10}} selects 1. The filter {"meta.x":{$exists:false}} selects 2 and 3, covering the empty object and absent parent; their union accounts for all three broad null matches.

Check your solution

  • Type 10 selects 1.
  • The missing-path filter selects 2 and 3.

12. For scalar ages null, missing, 9 and "9" in IDs 1โ€“4, select present non-null values and then identify which satisfy a numeric age rule.

Show hint

Non-null does not guarantee a numeric BSON type.

Show worked solution

The filter {age:{$ne:null}} selects 3 and 4. Only 3 has a numeric value; the string in 4 requires separate type validation even though it passes the non-null condition.

Check your solution

  • The filter selects 3 and 4.
  • Only 3 meets the numeric type rule.

13. For tags:[null], tags:null and missing tags in IDs 1โ€“3, compare query $type:10 with aggregation $type of the whole field.

Show hint

Query type can inspect array elements; aggregation type reports the field value.

Show worked solution

The query {tags:{$type:10}} matches 1 and 2. Aggregation {$type:"$tags"} reports array, null and missing respectively, so it distinguishes the whole field even when the array contains null.

Check your solution

  • The query matches 1 and 2.
  • The expression reports array, null and missing in order.

14. A report has 8 documents: 3 numeric, 2 null, 2 missing and 1 invalid. Check reconciliation and state how zero should be counted.

Show hint

Add mutually exclusive categories and treat zero as a number.

Show worked solution

The four categories sum to 8, so the population reconciles. A numeric zero belongs in the numeric category, subject to any separate business range rule, rather than being treated as missing.

Check your solution

  • Category counts sum to 8.
  • Zero is classified as numeric.

15. A display expression substitutes "Unknown" for null and missing. Explain what extra data a reviewer needs to distinguish them later.

Show hint

A shared label is a many-to-one transformation.

Show worked solution

Keep a separate state classification or the original field and its presence information. Both shapes display "Unknown", so the label alone cannot reconstruct whether the original key existed.

Check your solution

  • Both states can display "Unknown".
  • The retained state distinguishes missing from null.

16. A migration planned to convert two missing fields; counts change from missing 6, null 1, known 5 to missing 2, null 5, known 5. Reconcile totals and diagnose the variance.

Show hint

Compare both population totals and state transitions with the plan.

Show worked solution

Both snapshots total 12, but missing fell by four and null rose by four. The plan accounts for only two conversions, so investigate two extra transitions even though the total reconciles.

Check your solution

  • Each snapshot totals 12.
  • Two conversions exceed the plan.

17. A query {city:null} returns IDs 2 and 3, but a report requires only explicit null in a scalar schema. Repair it.

Show hint

Do not use broad null equality for this requirement.

Show worked solution

Use {city:{$type:10}} for the scalar schema and compare against the fixture. The explicit null remains while a missing city is excluded; array-valued schemas require additional care.

Check your solution

  • The replacement predicate tests type 10.
  • A missing city is excluded.

18. Design a five-document scalar test fixture for city validation that covers valid text, null, missing, empty text and a wrong type.

Show hint

Use different identifiers so each state is observable.

Show worked solution

One fixture is [{_id:1,city:"A"},{_id:2,city:null},{_id:3},{_id:4,city:""},{_id:5,city:7}]. Compare both selected IDs and application validation outcomes, since presence alone includes four documents. Test the domain rule independently.

Check your solution

  • ID 3 lacks city and ID 2 has null.
  • IDs 4 and 5 exercise empty and wrong-type values.

19. An API defines omit as unchanged, null as clear, and a separate remove action as deleting x. Starting with {_id:1,x:5}, map all three and compare existence results.

Show hint

Distinguish no targeted operation, $set and $unset.

Show worked solution

Omission leaves x:5, null maps to {$set:{x:null}}, and remove maps to {$unset:{x:""}}. The first two results have x; only the remove result lacks it. Driver serialization still needs testing.

Check your solution

  • Omission and null both retain the x key.
  • Only remove produces a missing x field.

20. For [{_id:1,dock:"N"},{_id:2,dock:null},{_id:3},{_id:4,dock:7},{_id:5,dock:""}], classify a report that accepts only nonempty scalar strings and reconcile counts.

Show hint

Keep missing, explicit null, valid and invalid categories separate.

Show worked solution

ID 1 is valid, 2 is explicit null, 3 is missing, and 4 and 5 are invalid under the stated rule. The counts 1+1+1+2=5 reconcile to the input; exclude IDs 4 and 5 from the valid-string subtotal and report them for review.

Check your solution

  • IDs 1, 2 and 3 occupy valid, null and missing categories respectively.
  • Invalid IDs 4 and 5 make the category total 5.

Key takeaways

  • Explicit null and a missing field can represent different states.
  • A null equality query can match both states.
  • Validate field type and update semantics separately.
  • Presence establishes a key, not a valid value.
  • $set to null retains a field while $unset removes it.
  • A display fallback can hide the difference between missing and null.

Official references