MongoDB $ifNull Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $ifNull?

$ifNull is MongoDB’s null coalescing expression. It returns the first value that is not null and not missing. If every candidate is null/missing, it returns the final replacement.

Remember
$ifNull = value ?? default

{ $ifNull: [ <expr>, <default> ] }

{ $ifNull: [ <a>, <b>, <default> ] }   // 5.0+

null / missing → use next / default
0, false, ""   → kept (not null)
UsePrefer
Default for null / missing$ifNull
Any boolean condition$cond
Many named cases$switch

How to Use $ifNull in MongoDB

List preferred values first, then the fallback you want when all are null.

  1. Choose an expression stage ($addFields or $project).
  2. Put the preferred field (or expression) first in the array.
  3. Add more candidates if needed, then a final default (literal or expression).
  4. Read the result as a cleaned field for reports, labels, or later math.
PieceRequired?Role
Input expression(s)YesTried left to right; first non-null wins
ReplacementYes (last item)Used when every input is null/missing

Pseudocode

Pseudocode
for each document:
    for each expression in $ifNull list (except last):
        value = evaluate(expression)
        if value is not null and not missing:
            result = value
            break
    else:
        result = evaluate(lastExpression)  // default
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while filling null gaps.

TopicDetail
TypeAggregation expression (not a find filter alone)
Classic syntax{ $ifNull: [ "$field", default ] }
Multi syntax (5.0+){ $ifNull: [ "$a", "$b", default ] }
Triggers fallbacknull, missing field, undefined
Does not trigger0, false, ""
vs $condNull-only shortcut vs any boolean test
Common pattern{ $ifNull: [ "$discount", 0 ] }

Live Preview

Simulate $ifNull: ["$nick", "$name", "Guest"]. Change what is stored and watch which value wins.

Same idea as the mongosh examples: prefer nick, then name, else "Guest".

Result
nick = "Sam"
name = (unused)
$ifNull → "Sam"

{ display: "Sam" }

Worked Walkthrough — Display Name

Rule: show nick if present, else name, else "Guest".

Calculation
Rule:
  $ifNull([ nick, name, "Guest" ])

nick = "Sam"          → "Sam"
nick = null, name = "Alex" → "Alex"
nick missing, name = "Pat" → "Pat"
both missing          → "Guest"

Not null:
  score = 0  → kept (zero is a value)

MongoDB Examples

We use a small profiles collection. First we default a missing nickname, then we try nick → name → Guest. Insert the sample data once in mongosh.

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.

mongosh
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:

mongosh
db.profiles.find()

Read those documents like this:

Field in MongoDBExamplePlain English
_id1 … 4Profile id for this lesson
nick"Sam" or nullOptional nickname (may be missing)
name"Alex"Full name (may be missing)
Picture
Fallback chain (left → right):

  nick  →  name  →  "Guest"

  "Sam" / Samuel     → "Sam"
  null  / Alex       → "Alex"
  (missing) / Pat    → "Pat"
  (missing)/(missing)→ "Guest"

How It Works

  1. Insert once. insertMany adds four profile documents.
  2. Null vs missing. Doc 2 has nick: null; docs 3–4 omit nick—both count as null for $ifNull.
  3. find() shows the same shape. What you inserted is what you get back—ready for $ifNull next.

Example 2 — Simple Default

Goal: add display as nickname, or "Guest" when nick is null or missing.

mongosh
db.profiles.aggregate([
  {
    $addFields: {
      display: {
        $ifNull: ["$nick", "Guest"]
      }
    }
  }
]);

How It Works

  1. Try nick first. Doc 1 has "Sam" → that value is kept.
  2. Null triggers default. Doc 2’s null is replaced with "Guest".
  3. Missing triggers default. Docs 3 and 4 have no nick → also "Guest".
  4. Name is unused here. Simple form only looks at one field plus a default.

Example 3 — Multi Fallback (nick → name → Guest)

Same profiles, but prefer nickname, then full name, then "Guest" (MongoDB 5.0+ multi-argument form).

mongosh
db.profiles.aggregate([
  {
    $addFields: {
      display: {
        $ifNull: ["$nick", "$name", "Guest"]
      }
    }
  }
]);

How It Works

  1. Same stored documents. Still using the four profiles from Example 1.
  2. First non-null wins. Sam keeps nick; Alex falls through to name; Pat uses name.
  3. Final default. Doc 4 has neither field → "Guest".
  4. Older MongoDB? Nest instead: { $ifNull: ["$nick", { $ifNull: ["$name", "Guest"] }] }.

Edge Cases & Pitfalls

Check these before relying on $ifNull.

zero

0 and "" are not null

$ifNull keeps 0, false, and empty strings. Use $cond if those should also fall back.

missing

Missing equals null here

A field that does not exist is treated like null—both use the replacement path.

cond

Need comparisons? Use $cond

$ifNull cannot test score >= 70. Reach for $cond for real if/else logic.

version

Multi-arg needs MongoDB 5.0+

Three-or-more argument lists are MongoDB 5.0+. Nest two-argument $ifNull calls on older versions.

Performance Notes

ApproachCostBest for
$ifNull alonePer-document checkDefaults, display labels
Multi-arg $ifNullFew extra checksnick → name → Guest chains
Store clean valuesNo runtime defaultHot paths / large collections

$ifNull is cheap. Prefer writing real defaults at insert time when you can. Filter early with $match when only some documents need cleanup.

Key Takeaways

  • Role: first non-null value, else a default.
  • Triggers: null and missing fields only.
  • Keeps: 0, false, and "".
  • Multi: chain candidates; last item is the final default.

One line: $ifNull answers “use this value, or that default if it is null/missing.”

Frequently Asked Questions

$ifNull returns the first non-null expression. If every input is null or missing, it returns the final replacement value. Missing fields and undefined count as null.
Classic form: { $ifNull: [ <expression>, <replacement> ] }. From MongoDB 5.0 you can pass more inputs: { $ifNull: [ <a>, <b>, …, <replacement> ] } and get the first non-null value.
No. Only null and missing/undefined trigger the fallback. 0, false, and "" are real values and are returned as-is.
$ifNull is only for null/missing defaults. $cond evaluates any boolean condition—use it for comparisons like score >= 70.
Yes. Use multiple arguments (MongoDB 5.0+): { $ifNull: [ "$nick", "$name", "Guest" ] }. Older style: nest $ifNull inside the replacement.
Inside aggregation expression stages such as $project and $addFields—not as a standalone find() filter by itself.

Next: $in

Check whether a value is present in an array of candidates.

$in tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful