$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.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $ifNull: [ <expression>, <replacement> ] }
⚙️ Parameters
| expression | The expression to inspect. |
|---|---|
| replacement value | The 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
- A missing field also triggers the fallback, without error
- Empty strings and arrays do not trigger; check with $eq/$size first when needed
- 4.4+ accepts multiple arguments: { $ifNull: ['$a', '$b', 'default'] } returns the first non-null
🏷️ Related Tags
💡 Related Cases
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.