Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Data Model & Data Types  ›  Lesson

Strings, Booleans and Null

String 12 minStrings are UTF-8 text matched exactly and case-sensitively, booleans are true or false rather than text, and a query for null matches both explicit nulls and missing fields.

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" })   // nothing

Boolean: 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 field

To 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 books

The shortcut

Before writing an equality filter, say the stored value out loud, character for character, with its type.

Finding signed booksStep 1 of 4
  1. 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.

quick drill

How many books does db.books.find({ author: "frank herbert" }) return?

quick drill

Which filter finds The Hobbit by its signed flag?

quick drill

How many books match { signed: null }?

quick drill

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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThree everyday types

A teammate stores a book's signed status as the text "yes" and searches authors with lower-case names. Explain what goes wrong with each, and what { signed: null } would return on the bookshop's books collection.