Strings, Booleans and Null
Someone searches the shop for "jane austen" and gets nothing, even though Emma is right there. Someone else marks signed books with the word "yes" and wonders why a filter for signed books misses half of them. Three everyday types, three everyday surprises.
The rule
Strings match exactly, booleans are not words, and null also means missing.
String: UTF-8 text, so any language or emoji is fine. Equality is exact and case-sensitive:
db.books.find({ author: "Jane Austen" }) // Emma
db.books.find({ author: "jane austen" }) // nothingBoolean: true or false, with no quotes. In our collection only The Hobbit has signed: true. The string "true" is a different value of a different type, so { signed: "true" } would not find it.
Null: an explicit "no value". The key rule: a query for null matches documents where the field is null or does not exist at all.
db.books.find({ signed: null })
// Dune, Neuromancer, Emma, Circe: none of them has a signed fieldTo tell the two cases apart, ask about the type instead. $type checks a field's BSON type by name:
db.books.find({ signed: { $type: "null" } }) // only fields actually set to null: none here
db.books.find({ title: { $type: "string" } }) // all five booksThe shortcut
Before writing an equality filter, say the stored value out loud, character for character, with its type.
Say the stored value
The Hobbit holds
signed: true, a boolean, with no quotes.
The trap is thinking null means "explicitly set to null". In a query it also sweeps up every document where the field is absent.
Drills
Answer fast — trust the rule.
How many books does db.books.find({ author: "frank herbert" }) return?
Which filter finds The Hobbit by its signed flag?
How many books match { signed: null }?
Which filter matches ONLY documents where signed is explicitly null?
Remember
- Strings match exactly, booleans are not words, and null also means missing.
- Shortcut: say the stored value aloud, with its type, before you filter on it.
- Trap:
{ field: null }returns documents that lack the field; use$type: "null"for real nulls.
