$ifNull (Null Fallback)

Last updated: 2026-10-09

$ifNull (Null Fallback)

$ifNull returns a replacement value when an expression resolves to null or a field is missing — the most common operator for handling empty data. Typical uses: providing a default bio for missing profiles or replacing null prices with 0 before arithmetic. Since MongoDB 4.4 it accepts multiple arguments and returns the first non-null value. It only triggers on null and missing; empty strings and empty arrays pass through, so combine with $eq or $size when those must be treated as empty.

CategorySet, Condition & Conversion
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $ifNull: [ <expression>, <replacement> ] }

⚙️ Parameters

expressionThe expression to inspect.
replacement valueThe value returned when the expression is null or missing.

Returns:The original value when not null, otherwise the replacement

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $ifNull: default bio when missing
db.users.aggregate([
  { $project: {
      bio: { $ifNull: ['$bio', 'This user stays low-key'] }
  } }
])

Output:

{ '_id': 1, 'bio': 'This user stays low-key' }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QDoes a missing field trigger the fallback?
AYes — missing behaves like null and returns the replacement.
QDoes an empty string trigger the fallback?
ANo, it only fires on null and missing.
QHow do I use multiple fallbacks?
APass several arguments on 4.4+; the first non-null wins.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏