$ifNull

The `$ifNull` operator is used to evaluate an expression and return a specified value if the expression resolves to `null`.

Syntax

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

Parameters

expressionobjectrequired

The expression to evaluate

replacement-valueobjectrequired

The value to return if the expression evaluates to `null`

Examples

Default value for missing intern field

To ensure that the `$staff.totalStaff.intern` field is always a number, you can use `$ifNull` to replace `null` values with `0`.

Query:

db.stores.aggregate([
  {
    $project: {
      name: 1,
      interns: { $ifNull: ["$staff.totalStaff.intern", 0] }
    }
  },
  { $limit: 3 } 
])

Output:

[
  { "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5", "name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile", "interns": 0 },
  { "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41", "name": "VanArsdel, Ltd. | Musical Instrument Outlet - East Cassie", "interns": 0 },
  { "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34", "name": "Northwind Traders | Bed and Bath Place - West Oraland", "interns": 0 }
]

Related