Example 1 — Sample Data
Imagine four user profiles. Some have a nickname, some have only a name, and one has neither. We save them in a collection named profiles.
db.profiles.insertMany([
{ _id: 1, nick: "Sam", name: "Samuel" },
{ _id: 2, nick: null, name: "Alex" },
{ _id: 3, name: "Pat" },
{ _id: 4 }
]); How the Data Is Stored in MongoDB
After the insert, MongoDB keeps four documents in profiles. Run find() to see them:
db.profiles.find() Read those documents like this:
| Field in MongoDB | Example | Plain English |
|---|---|---|
_id | 1 … 4 | Profile id for this lesson |
nick | "Sam" or null | Optional nickname (may be missing) |
name | "Alex" | Full name (may be missing) |
Fallback chain (left → right):
nick → name → "Guest"
"Sam" / Samuel → "Sam"
null / Alex → "Alex"
(missing) / Pat → "Pat"
(missing)/(missing)→ "Guest" How It Works
- Insert once.
insertManyadds four profile documents. - Null vs missing. Doc 2 has
nick: null; docs 3–4 omitnick—both count as null for$ifNull. - find() shows the same shape. What you inserted is what you get back—ready for
$ifNullnext.

