MongoDB $ifNull Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Null Handling

What You’ll Learn

The $ifNull operator supplies a default value when a field is null or missing. Use it to clean up reports, fill gaps in user profiles, and avoid null checks in application code.

01

Null Fallback

Default when null/missing.

02

Syntax

Two-element array form.

03

Missing Fields

Treats absent keys as null.

04

$project Stage

Add safe computed fields.

05

Use Cases

Defaults, cleanup, reports.

06

Chaining

Try multiple fallbacks.

Definition and Usage

In MongoDB’s aggregation framework, the $ifNull operator evaluates an expression and returns it when the value is present. If the expression is null or the field is missing, MongoDB returns a replacement default instead. For example, show "Guest" when a user has no displayName.

💡
Beginner Tip

$ifNull only checks for null and missing fields. It does not treat 0, false, or "" as null — use $cond when you need those rules.

📝 Syntax

$ifNull takes exactly two expressions in an array. The second value is the fallback:

mongosh
{ $ifNull: [ <expression>, <replacement-if-null> ] }

Chained fallbacks (try field A, then B, then a literal default):

mongosh
{ $ifNull: [ "$fieldA", { $ifNull: [ "$fieldB", "default" ] } ] }

Syntax Rules

  • First argument — the value to return when it is not null and not missing.
  • Second argument — the default when the first is null or the field does not exist.
  • Both arguments can be field references, literals, or nested aggregation expressions.
  • Missing document fields are treated the same as null.
  • 0, false, and empty strings are not replaced.
  • Use inside $project, $addFields, $set, or $group.

💡 $ifNull vs $cond

$ifNull — shortcut when you only need a default for null or missing values
$cond — general if-then-else on any boolean condition
Use $ifNull for simple fallbacks; use $cond for comparisons like score >= 70

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (null coalescing)
Syntax{ $ifNull: [ expression, replacement ] }
Triggers fallbacknull or missing field only
Does not replace0, false, ""
Common stages$project, $addFields, $set, $group
String default
{
  $ifNull: [
    "$email",
    "unknown@example.com"
  ]
}

Fill missing email

Numeric default
{
  $ifNull: [
    "$discount",
    0
  ]
}

Null discount → 0

Chained
{
  $ifNull: [
    "$nickname",
    {
      $ifNull: [
        "$name",
        "Guest"
      ]
    }
  ]
}

Try nickname, then name

Expression
{
  $ifNull: [
    "$total",
    {
      $multiply: [
        "$qty",
        "$price"
      ]
    }
  ]
}

Computed fallback

Examples Gallery

Fill missing emails, default numeric fields, chain fallbacks across profile fields, and compute safe totals with $ifNull.

📚 Basic Default Value

Use a users collection and replace missing email fields with a placeholder.

Sample Input Documents

Suppose you have a users collection where some profiles omit email:

mongosh
[
  { "_id": ObjectId("609c26812e9274a86871bc6a"), "name": "Alice",   "email": "alice@example.com" },
  { "_id": ObjectId("609c26812e9274a86871bc6b"), "name": "Bob",     "email": null },
  { "_id": ObjectId("609c26812e9274a86871bc6c"), "name": "Charlie" }
]

Charlie’s document has no email key at all — MongoDB treats that as missing, same as null.

Example 1 — Default for Missing Email

Return the email when present; otherwise use "unknown@example.com":

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      safeEmail: {
        $ifNull: ["$email", "unknown@example.com"]
      }
    }
  }
])

How It Works

  • Alice keeps her real email because the field exists and is not null.
  • Bob’s explicit null triggers the fallback.
  • Charlie’s missing field is treated like null — same result as Bob.

📈 Practical Patterns

Numeric defaults, display-name chains, and computed fallbacks in orders.

Example 2 — Numeric Default for Discount

Orders without a discount should count as 0 in reports:

mongosh
db.orders.aggregate([
  {
    $addFields: {
      discountApplied: {
        $ifNull: ["$discount", 0]
      }
    }
  }
])

// discount: 10  → discountApplied: 10
// discount: null → discountApplied: 0
// (field missing) → discountApplied: 0

How It Works

$addFields keeps all existing fields and adds discountApplied. A real 0 discount would stay 0 — only null and missing values are replaced.

Example 3 — Chained Fallback for Display Name

Prefer nickname, then name, then "Guest":

mongosh
db.users.aggregate([
  {
    $project: {
      displayName: {
        $ifNull: [
          "$nickname",
          { $ifNull: ["$name", "Guest"] }
        ]
      }
    }
  }
])

How It Works

The inner $ifNull runs only when nickname is null or missing. This pattern is common for user-facing labels without storing a redundant field.

Example 4 — Computed Fallback Expression

Use a calculated total when total was never stored on the document:

mongosh
db.orders.aggregate([
  {
    $project: {
      product: 1,
      finalTotal: {
        $ifNull: [
          "$total",
          { $multiply: ["$qty", "$price"] }
        ]
      }
    }
  }
])

// total: 120        → finalTotal: 120
// total: null       → finalTotal: qty × price
// total missing     → finalTotal: qty × price

How It Works

The second argument does not have to be a literal — it can be any expression. MongoDB evaluates the fallback only when the first value is null or missing.

🚀 Use Cases

  • Default value assignment — fill null or missing fields with sensible placeholders in reports.
  • Data cleanup — normalize inconsistent documents before exporting or displaying.
  • User profiles — show display names, avatars, or contact info with chained fallbacks.
  • Financial reporting — treat null discounts, fees, or totals as zero or computed values.

🧠 How $ifNull Works

1

MongoDB evaluates the first expression

It reads a field reference or nested expression for the current document.

Input
2

$ifNull checks for null or missing

If the value exists and is not null, that value is returned immediately.

Check
3

Otherwise the replacement is used

The second expression — literal, field, or nested operator — becomes the result.

Fallback
=

Safe field value per document

Reports and APIs get consistent data without null-handling logic in your app.

Conclusion

The $ifNull operator is the simplest way to handle null and missing values inside MongoDB aggregation pipelines. It keeps reports readable and reduces defensive coding in your application layer.

Start with single-field defaults, then chain nested $ifNull calls when you need multiple fallbacks. For boolean conditions (not just null checks), use $cond instead.

💡 Best Practices

✅ Do

  • Use $ifNull for null and missing fields — it is shorter than equivalent $cond
  • Chain nested $ifNull for nickname → name → default patterns
  • Keep fallback types consistent (string with string, number with number)
  • Test documents with missing keys, explicit null, and real values
  • Combine with $project or $addFields for clean output fields

❌ Don’t

  • Expect $ifNull to replace 0, false, or ""
  • Use $cond when a simple null fallback is enough
  • Forget that only two arguments are allowed per $ifNull call
  • Assume nested fallbacks run in parallel — they evaluate left to right
  • Store large default objects in every pipeline — consider $let for reuse

Key Takeaways

Knowledge Unlocked

Five things to remember about $ifNull

Use these points when handling null or missing values in MongoDB.

5
Core concepts
📝 02

[ expr, default ]

Two-element array.

Syntax
📏 03

Missing = null

Absent fields count.

Rule
🛠 04

Chain Nested

Multiple fallbacks.

Pattern
05

Not for 0 / ""

Use $cond instead.

Important

❓ Frequently Asked Questions

$ifNull returns the first expression when it is not null and not missing. If the first value is null or the field does not exist, it returns the second expression as a default.
The syntax is { $ifNull: [ <expression>, <replacement-if-null> ] }. The second value is used only when the first evaluates to null or is missing.
No. $ifNull only handles null and missing fields. Empty strings (""), 0, and false are real values and are returned as-is.
$ifNull is a shortcut for null/missing fallbacks. $cond evaluates any boolean condition — use it when you need comparisons like score >= 70.
Yes. Nest $ifNull in the replacement expression: { $ifNull: [ "$a", { $ifNull: [ "$b", "default" ] } ] } tries $a, then $b, then the final default.

Continue the Operator Series

Move on to $in for membership tests, or review $hour for extracting time from dates.

Next: $in →

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.

5 people found this page helpful