Skip to content

$ifNull

The $ifNull operator returns the first non-null expression from the provided list of two expressions.


📌 Syntax

{ "$ifNull": [ <expression1>, <fallback> ] }

✅ Base Example 1 – Provide Default Value

📥 Input Document

{ "nickname": null }

📌 Expression

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

📤 Output

"Guest"

✅ Base Example 2 – Use Alternative Field

📥 Input Document

{ "username": "alice" }

📌 Expression

{ "$ifNull": ["$nickname", "$username"] }

📤 Output

"alice"

🧱 Ecommerce Example – Show Discount Label

📌 Pipeline

[
  { "$unwind": "$items" },
  {
    "$project": {
      "product": "$items.name",
      "discountLabel": {
        "$ifNull": ["$items.discountLabel", "Standard"]
      }
    }
  }
]

📥 Input Document

{
  "items": [
    { "name": "Shoes", "discountLabel": "Spring Sale" },
    { "name": "Socks" }
  ]
}

📤 Output

[
  { "product": "Shoes", "discountLabel": "Spring Sale" },
  { "product": "Socks", "discountLabel": "Standard" }
]

🔧 Common Use Cases

  • Provide fallback/default values
  • Avoid nulls in views or exports
  • Chain with $cond or $switch

  • $cond, $switch, $coalesce, $or

🧠 Notes

  • Returns expression1 if it's not null or missing
  • Otherwise returns fallback